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.



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

clock April 17, 2015 09:42 by author Rebecca

In this post, I will tell you how to insert data page with example code in ASP.NET Webpages 3.1.

Follow these steps to insert data page:

Step 1

Click Databases. then click on Home in the ribbon menu, and Click on New Query. Let's copy this following code:

CREATE TABLE Games
(
Id INT NOT NULL PRIMARY KEY IDENTITY,
GameName NVARCHAR(200) NOT NULL,
ReleaseDate DateTime NOT NULL,
mTitle NVARCHAR(200) NOT NULL,
mDescription NVARCHAR(200) NOT NULL,
Text nText NOT NULL
);

Step 2

Click Execute.

Now, you have created a new table and a few columns so we can perform our CRUD operations. In the Create page copy the following:

@{
var GameName = "";
DateTime ReleaseDate = DateTime.UtcNow;
var mTitle = "";
var mDescription = "";
var Text ="";

Then you have created 5 variables which you will use to collect the user-entered data and then insert the data into a database. The second variable is a DateTime data type. The second column in the database is for DateTime. The user will not have to specify the ReleaseDate, as it has been set as the current UTC date and time.

if (IsPost)
{
    GameName = Request["GameName"];
    mTitle = Request["mTitle"];
    mDescription = Request["mDescription"];
    Text = Request.Unvalidated("Text");
 
    Validation.RequireFields("GameName", "mTitle", "mDescription", "Text");


var SQLINSERT = "INSERT INTO Games (GameName, ReleaseDate, mTitle, mDescription, Text) VALUES (@0, @1, @2, @3, @4)";

When the user submits the data we request the values from the HTML elements. The Request.Unvalidated allows the user to type anything they like. By default, ASP.NET will not allow you to type HTML and JavaScript; this is a security measure to avoid XSS attacks.

The validation ensures that no field is left blank. You have to separate each field with a comma. Now, SQLINSERT is our database command. You can specify the column names and then the values which will be inserted. When we use @0, @1 we pass the data as parameters; this is the safest way to do this as it avoids XSS attacks. Always pass the data like this:

    if (Validation.IsValid())
    {
        try
        {
            var db = Database.Open("StarterSite");
            db.Execute(SQLINSERT, GameName, ReleaseDate, mTitle, mDescription, Text);
            Response.Write("Data Saved!");
        }catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
 
}
 
}


Lastly, we ensure that the data entered is valid, and then use a try catch block to execute the database command. The db.Execute method takes two arguments (string command, param object[] args); the second argument is basically the parameters. When you specify the parameters in the Execute method you need to make sure that it is in the right order, otherwise you will get errors. For example, try entering:

db.Execute(SQLINSERT, GameName, mTitle, ReleaseDate,  mDescription, Text);

This will flag an error because the second column expects a data type of DateTime. It is good practise to keep the order of the columns as they appear in the table.

Full HTML Script

<form method="post">
<fieldset>
<legend>Insert Data</legend>
@Html.ValidationSummary(true)
<div>
<label>Game Name</label>
<input type="text" value="@GameName" name="GameName"/>
@Html.ValidationMessage("GameName")
</div>
 
<div>
<label>Meta Title</label>
<input type="text" value="@mTitle" name="mTitle"/>
@Html.ValidationMessage("mTitle")
</div>
 
<div>
<label>Meta Description</label>
<input type="text" value="@mDescription" name="mDescription"/>
@Html.ValidationMessage("mDescription")
</div>
 
 
<div>
<label>Text</label>
<textarea class="ckeditor" name="Text">@Text</textarea>
@Html.ValidationMessage("Text")
</div>
 
<input type="submit"/>
</fieldset>
 
</form>
 
<script src="/ckeditor/ckeditor.js"></script>

One thing that should be explained is the <script> tag. We will use CKEditor for our <textarea>, as this allows us to add HTML styles.

Finaaly, you can run the page and add a new entry, and remember the title for the GameName. Make sure the GameName does not have any spaces or characters; stick with numbers, letters and dashes only.

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.



ASP.NET Web Pages 3.1 Hosting - HostForLIFE.eu :: First Look at ASP.NET Web Pages

clock April 13, 2015 06:56 by author Rebecca

As you know, ASP.NET comes in three types: MVC, Web Forms and WebPages.
1. Web Forms - This is the classic ASP.NET framework; it has all the server side controls and is used for creating dynamic websites. It does have a steep learning curve and controls most of the mark-up so there is little control. It is event-driven and is good for RAD (Rapid Application Development).

2. MVC - Model-View-Controller, this framework also has a steep learning curve, however, it is ideal for developers who like to have control over their websites and like to separate logic and UI. It is ideal for team based work.
3. Web Pages – This is the easiest of all and is what you’ll be learning. It uses the Razor View Engine and is easy to learn providing you have a good understanding of HTML, CSS, JavaScript and either C# or Visual Basic.

Today, I will introduce to you about ASP.NET WebPages.

ASP.NET WebPages is a lightweight web framework for creating rich websites using Microsoft C# or Visual Basic. The framework is the ideal starting place for newcomers to ASP.NET, as well as experienced developers who wish to get into ASP.NET development.If you're interested in learning basic programming, ASP.NET WebPages gives you the different feels between any JavaScript in a web page that you've ever written before.

You can use ASP.NET WebPages to create dynamic web pages. A simple HTML web page is static; its content is determined by the fixed HTML markup that's in the page. Dynamic pages like those you create with ASP.NET Web Pages let you create the page content on the fly, by using code. Dynamic pages let you do all sorts of things too. You can ask a user for input by using a form and then change what the page displays or how it looks. You can take information from a user, save it in a database, and then list it later. You can send email from your site. You can interact with other services on the web (for example, a mapping service) and produce pages that integrate information from those sources. Most examples of using ASP.NET Web Pages with Razor syntax use C#. But the Razor syntax also supports Visual Basic. To program an ASP.NET web page in Visual Basic, you create a web page with a .vbhtml filename extension, and then add Visual Basic code.

You'll need to use IDE when working with Web Pages and the ideal IDE that will compatible with ASP.NET WebPages is Microsoft WebMatrix. Microsoft WebMatrix is a small IDE which was released alongside ASP.NET Web Pages. WebMatrix is a tool that integrates a web page editor, a database utility, a web server for testing pages, and features for publishing your website to the Internet. WebMatrix is free, and it's easy to install and easy to use. It also works for just plain HTML pages, as well as for other technologies like PHP.

WebMatrix contains:

1. Web Pages examples and templates
2.A web server language (Razor using VB or C#)
3. A web server (IIS Express)
4. A database server (SQL Server Compact)
5. A full web development framework (ASP.NET)

With WebMatrix you can start from scratch with an empty web site and a blank page, or build on open source applications from a "Web Application Gallery". Both PHP and ASP.NET applications are available, such as Umbraco, DotNetNuke, Drupal, Joomla, WordPress and many more. WebMatrix also has built-in tools for security, search engine optimization, and web publishing. The skills and code you develop with WebMatrix can seamlessly be transformed to fully professional ASP.NET applications.

But, you don't actually have to use WebMatrix to work with ASP.NET Web Pages. You can create pages by using a text editor too, for example, and test pages by using a web server that you have access to.

HostForLIFE.eu ASP.NET WebPages 3.1 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



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