European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

ASP.NET WebPages 3.1 Hosting - HostForLIFE.eu :: ASP.NET WebPages 3.1 Cookies

clock April 13, 2016 23:33 by author Anthony

In this article I will make tutorial about how to make read, write and delete cookies in ASP.NET WebPages 3.1. Cookies are a small text file containing information about a user; for example, a cookie may contain information on the last video the user watched or what items they have in their shopping cart. Many e-commerce websites like Amazon save cookies to your computer that can either collect your data or store the items in the shopping cart.

In Microsoft WebMatrix create a new website based of the Personal Site template name the website Cookies. Next in the root folder create a page called Settings.cshtml.

Writing a Cookie

Writing, reading and deleting a cookie are all fairly simple, as will be displayed in this tutorial. We will give the user an option to choose between two site layouts, and once they select which one they prefer a cookie will be saved to their computer. This will be read by the main master page and it will load the correct style sheet.

Writing Cookie Syntax

Response.Cookies["Cookie Name"].Value = "Value";
Response.Cookies["Cookie Name"].Expires = DateTime.Now.Add (Either, days, months, years, minutes etc);

If you do not specify when the cookie expires then it will automatically expire at the end of the session (when the user closes their browser).

In the Settings page insert this code:

C# Code:

@{

if (IsPost){   

    var layout = Request["layout"];

    if (layout == "Dark"){
         Response.Cookies["Theme"].Value = "Dark";
         Response.Cookies["Theme"].Expires = DateTime.Now.AddYears(1);    
    }
  }

}

Here we have var layout which requests the HTML control layout. After the user is given an option, if they choose Dark a cookie with the name Theme and value Dark will be saved to their browser, and it expires in one year.

HTML Code:

<form method="post">

<fieldset>
<legend><h4>Choose Layout</h4></legend>
    <label>Select Layout</label>

    <select name="layout">
    <option value="Dark">Dark</option>
    <option value="Default">Default</option>
    </select>

    <input type="submit" />
</fieldset>
</form>

Leave the option default for now because we will come back to it. Now run the page and select Dark as your theme; the page will refresh. Then in your chosen browser go to your stored cookies and you should see that a new cookie has been made called Theme (this should be under a folder called localhost by default) with the value Dark. For chrome users simply copy and paste this in the address bar of your browser: chrome://chrome/settings/cookies.

Reading Cookies

The domain which inserts the cookie can read the cookie. So for example, if thecodingguys.net writes a cookie called "Theme" Google.com cannot read that cookie. This will apply to sub-domains as well; m.thecodingguys.net cannot read a cookie which was created by www.thecodingguys.net.
Now the cookie should be inserted in your browser. Before we can read the cookie we need to make a new layout, so we will make a new style sheet. In the content folder copy the Site.css file and paste it in that folder, and re-name it to Site_Two.css. Next open the Site_Two.css find the body style and change the background colour to a colour of your choice (make sure it is different than the default).

Navigate to the layouts folder and open the _SIteLayout.cshtml file. Find the linked style sheet (below title tag) and replace it with:

C# Code:

@if (Request.Cookies["Theme"] != null){//MAKE SURE COOKIE EXIST

    if (Request.Cookies["Theme"].Value == "Dark"){//READ COOKIE VALUE
         <link href="~/Content/Site_Two.css" rel="stylesheet" />
    }
}else{
  <link href="~/Content/Site.css" rel="stylesheet" />   //IF COOKIES DOES NOT EXIST LOAD DEFAULT STYLESHEET
}

The first If Statement requests the cookie by name, not the cookie value but just the cookie named Theme. We need to make sure it is not null (meaning it exists), and then if it exists read the value. If the value is Dark, and it will load the second style sheet. Now if the cookie is not there it will load the default style sheet.

Deleting Cookies

Return to the Settings.cshtml file and add this to the If Statement:

C# Code:

else if (layout == "Default"){
         Response.Cookies["Theme"].Expires = DateTime.Now.AddYears(-1);
    }

Deleting a cookie is simple: on submit if the user selects the Default option the cookie is deleted. There is no direct command to delete the cookie, all we do is set the expiry date to a previous date. In this case it is set to the year before meaning it has expired and the browser will delete it.

Summary

Reading, writing and deleting cookies is quite simple. Cookies are very useful when you want to have full control overs users and provide extra functionality. Remember that cookies are client sided so users can disable them if they want to. Also remember that there are some laws (EU Law) regarding cookies, so make sure you inform users you are saving cookies.

 

 

HostForLIFE.eu ASP.NET WebPages 3.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Web Pages 3.1 with Free ASP.NET Hosting - HostForLIFE.eu :: SQL Syntax to Perform a Task for Database

clock May 8, 2015 06:10 by author Rebecca

At times you will need to access a database to perform tasks such as updating and removing information. Here, I will show you the most commonly used SQL statements such as reading from database, updating database and deleting database entries.

Connecting to Database

To connect to a database you use the Database.Open command then in brackets you give the database name. The database must be in the app_data folder (unless you specified it somewhere else in the web.config).

Here are the example:

Database.Open("DatabaseName");

The database name must be wrapped in quotation marks; you do not specify the database extension.

Read and Select Data in Database

The select statement will read data from a database. The syntax is as follows:

"SELECT columnname FROM tablename";

To select all the columns you use an asterisk:

"SELECT * FROM tablename";

Insert Data in Database

The insert statement will insert data into the database:

"INSERT INTO tablename (column 1, 2, 3 5) VALUES (@1, @2)";

Updating Database

"Update tablename set column1=@1, column2=@2";

Detele Data in Database

"DELETE FROM tablename WHERE column=value";

Filter Data Records

The where clause is used to filter records like this:

"SELECT  * FROM tablename WHERE columnname = 'value';

HostForLIFE.eu ASP.NET WebPages 3.1 with Free ASP.NET Hosting
Try our ASP.NET WebPages 3.1 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



ASP.NET Web Pages 3.1 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Read Data Page

clock April 21, 2015 06:33 by author Rebecca

To continue the last tutorial about how to insert data page in ASP.NET Web Pages 3.1, today I'm gonna tell you how to read the data page that we have inserted with example code.

These are the steps to read the data page:

Step 1

The first thing to do is create a variable db which opens the database. Then, you will have another variable called GameName which is set to get the RouteValue from the URL (we will use routing for clean URLS). Beneath that is an If Statement which checks if GameName is null, if it is, the user is redirected back to the home page.

In the Read.cshtml file insert following code:

@{
   
var db = Database.Open("StarterSite");
 
var GameName = Context.GetRouteValue("GameName");
if (GameName == null){Response.Redirect("~/");}
 
var SQLREAD = "SELECT * From Games Where GameName=@0";
var data = db.QuerySingle(SQLREAD, GameName);
 
var Id = data.Id;
var Text =  data.Text;

Page.Title = data.mTitle;
Page.mDescription = data.mDescription;

Step 2

Next you have a SQL command which will get the data from the database, the where clause is used to filter out results. The db.QuerySingle retrieves one result from the database, and we provide two arguments, the command and parameter, which is the GameName variable. The GameName variable stores the current page name. For example, our route has the following pattern:

RouteTable.Routes.MapWebPageRoute("games/{GameName}", "~/Read.cshtml");

When you go to an address like games/infamous the GameName variable has the value infamous, so the SQL command can be translated to:

var SQLREAD = "SELECT * From Games Where GameName=’infamous’";

Step 3

The data variable is now set to retrieve data from the database and only for the current page, since the where clause has filtered out the rows. Usually you only want to retrieve one row and place the data where you would like it to go. This is easily done when you type data after the dot (period): you specify the column name and the data for that row will be displayed. You can create the ID variable because it's a need to output the result a few times, as seen below.

<h2>@data.GameName</h2>
 
@Html.Raw(Text)
 
<span>@data.ReleaseDate - <a href="/update.cshtml?id=@Id">Edit Page</a> | <a href="/delete.cshtml?id=@Id&[email protected]">Delete Page</a></span>

The Html.Raw method will render the HTML properly, and this is another built-in ASP.NET security feature. If you do not use Html.Raw, you will get the HTML source printing out. The ?id=@id is a parameter and is used to pass data to the other pages. For example, when the user goes to the update page it will request the value of ID and will load that row from the database. So if ID= 1 it will load row 1. The same applies for delete page, although instead of updating the page it will be deleted. The returnurl as seen above is used to redirect the user back if the user rejects the confirmation to delete the page.
Here is the ouput example:

Step 4

Now we will add one more read data page. In the Default.cshtml page replace the code with this below:

@{
   
var db = Database.Open("StarterSite");
 
var SQLREAD = "SELECT * From Games";
var data = db.Query(SQLREAD);
 
}

<h2>Recent Games</h2>
 
<ul>
 
@foreach (var game in data)
{
    <li><a href="/games/@game.GameName">@game.GameName</a></li>
}
 
</ul>

This time we used the db.Query method. This gets all the rows from the table. Then we displayed all the results in an unordered list, which will allow us to view the games list from the default page instead of having to type it in the address bar.
Here is the ouput example:

HostForLIFE.eu ASP.NET WebPages 3.1 with Free ASP.NET Hosting
Try our ASP.NET WebPages 3.1 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in