European Windows 2012 Hosting BLOG

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

SQL Server 2014 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Move TempDB from one Drive to Another Drive

clock May 12, 2015 07:30 by author Rebecca

When you found that your TempDB log file is filled up, you will come across following errors in log file:
Source: MSSQLSERVER
Event ID: 17052
Description: The LOG FILE FOR DATABASE 'tempdb' IS FULL.
Back up the TRANSACTION LOG FOR the DATABASE TO free
up SOME LOG SPACE

So, you have to move the TempDB to different drive. Moving the TempDB to another drive will help the growth of the file. Sometimes user also moves to different drive due to performance reasons as keeping TempDB on a different drive from your main database helps. By this article, I'm gonna show you how to move TempDB from one drive to another drive.

There are major two reasons why TempDB needs to move from one drive to other drive:
1) TempDB grows big and the existing drive does not have enough space.
2) Moving TempDB to another file group which is on different physical drive helps to improve database disk read, as they can be read simultaneously.

You can follow the direction below exactly to move database and log from one drive (c:) to another drive (d:) and (e:)

Make sure that TempDB is set to autogrow and do not set a maximum size for TempDB. If the current drive is too full to allow autogrow events, then arrange a bigger drive, or add files to TempDB on another device (using ALTER DATABASE as described below and allow those files to autogrow).

1. Open Query Analyzer and connect to your server. Run this script to get the names of the files used for TempDB:

USE TempDB
GO
EXEC sp_helpfile
GO


Results will be something like:
name fileid filename filegroup size
——- —— ————————————————————– ———- ——-
tempdev 1 C:Program FilesMicrosoft SQL ServerMSSQLdatatempdb.mdf PRIMARY 16000 KB
templog 2 C:Program FilesMicrosoft SQL ServerMSSQLdatatemplog.ldf NULL 1024 KB

2. Along with other information related to the database, the names of the files are usually tempdev and demplog by default. These names will be used in next statement. Run following code, to move mdf and ldf files:

USE master
GO
ALTER DATABASE TempDB MODIFY FILE
(NAME = tempdev, FILENAME = 'd:datatempdb.mdf')
GO
ALTER DATABASE TempDB MODIFY FILE
(NAME = templog, FILENAME = 'e:datatemplog.ldf')
GO


The definition of the TempDB is changed. However, no changes are made to TempDB till SQL Server restarts. Please stop and restart SQL Server and it will create TempDB files in new locations.

HostForLIFE.eu SQL Server 2014 with Free ASP.NET Hosting
Try our SQL Server 2014 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 :: 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.



WCF with Free ASP.NET Hosting - HostForLIFE.eu :: Creating a WCF Data Service

clock May 4, 2015 07:47 by author Rebecca

Here in this tutorial, you are going to follow a simple step by step approach to create a WCF Data Service. You need Visual Studio 2010 IDE & SQL Server in your machine as prerequisites for building WCF Data Service. It would be nice if you have the basic .NET knowledge. Let's get started!

Step 1

Open Visual studio 2010 and create a Web -> ASP.NET Web Application with a language of your choice, either C# or VB. I’ve used C# throughout the lesson. The reason why we are creating an ASP.NET Web application is because in order to host and consume the WCF Data Service we need a hosting and client application.

Step 2

Once the application is created, you need a DataModel where it is going to be served. So let’s create a SQL Server database. Right click on the App_Data -> Create SQL Server database and define the schema as below and let’s feed some values into our newly created database table.

Step 3

You have your Database and Table ready, now it’s time for you to create an Entity Data Model. Right click on the project and Add New item -> Select ADO.NET Entity Data Model, a Wizard pops up, proceed further with it. Below screenshots helps you building a Model.

Step 4

Now, you are done with Entity Model and for our Schema structure, this how the Model looks:

Step 5

You are good with our basic implementation in-order to adopt a WCF Data Service into our application. Ready to go. Let’s create a WCF Data Service. Right click on the Project -> Add New Item -> Select WCF Data Service.

Step 6

WCF creates us a basic template code for us to start with.

Step 7

Before moving forward, let us keep our Database Entity name handy. It can be found in Web.Config under Connection String.

Step 8

Here you have replaced the template code with EntityName and Set of rules which decides the rights of access.

Step 9

If you run the application or just hit F5 selecting the WCF Data Service file. It opens up a browser and navigates us to http://localhost:/WCFDataFilename.svc . You can see a XML document with title holds to the Entity Name we created.

Step 10

To get the full database values as a XML model, just postfix the Entity Name with URL. As below:

Step 11

Quite simple right! You do have some syntax approach in accessing the resource via OData. For example, if you need a Single record, access it like below:

 

 

HostForLIFE.eu WCF with Free ASP.NET Hosting
Try our WCF 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.



SQL Server 2014 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Change Compatibility of Database to New SQL Version

clock April 28, 2015 06:12 by author Rebecca

In this post, I would like to show you how to change compatibility of database to SQL Server 2014. Maybe you have installed SQL Server 2014 and attached a database file from previous version of SQL Server. Right after attaching database, you were not able to work with the latest features of Cardinality Estimation. This problem is caused by the database compatibility was still set of the earlier version of SQL Server. To use most of the latest features of SQL Server 2014, you have to change the compatibility level of the database to the latest version.

Here are two different ways how we can change the compatibility of database to SQL Server 2014’s version:

1. Using Management Studio

For this method first to go database and right click over it. Now select properties.

On this below screen user can change the compatibility level to 120:

2. Using T-SQL Script

You can execute following script and change the compatibility settings to 120:
USE [master]
GO
ALTER DATABASE [AdventureWorks2012] SET COMPATIBILITY_LEVEL = 120
GO

Congratulations, you're done!

HostForLIFE.eu SQL Server 2014 with Free ASP.NET Hosting
Try our SQL Server 2014 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. 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 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.



WCF with Free ASP.NET Hosting - HostForLIFE.eu :: How to Create and Host a WCF Service in a Console Application

clock April 20, 2015 06:52 by author Rebecca

In this tutorial, I will explain to Self Host your WCF Service in a Console Application step by step. In order to host a WCF Service, you  need a managed process, a ServiceHost instance and an endpoint configured forWCF Service. You can host aWCF Service in following different possible ways:

1. Hosting in a Managed Application/ Self Hosting

  • Console Application
  • Windows/WPF Application
  • Windows Service

2.  Hosting on Web Server

  • IIS 6.0 (ASP.NET Application supports only HTTP)
  • Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ

Self Hosting a WCF Service in a console application is comparatively easy as well as flexible because we can achieve the purpose by writing few lines of code.

Step 1

Let’s first Create a Simple WCF Service i.e. a StudentService and then host in a Console application. StudentService having service operation GetStudentInfo that takes StudentId as parameter and returns student name. Open Visual Studio and Create a new Class Library Project, name it as “StudentService” and press “OK” button.

Then, right click on project and Add a new “WCF Service” to this Class Library Project.

It will add Service Contract (IStudentService) and it’s implementation class (StudentService) to class library project. Also, it will add a reference to System.ServiceModel.
Code for IStudentService interface will be as follows:

 [ServiceContract] public interface IStudentService
 {
     [OperationContract]
     string GetStudentInfo(int studentId);
 }
And following is the code for StudentService implementation class:
      public class StudentService : IStudentService
     {
         public string GetStudentInfo(int studentId)
         {
             string studentName = string.Empty;
             switch (studentId)
             {
                 case 1:
                     {
                         studentName = “Your Name”;
                         break;
                     }
                 case 2:
                     {
                         studentName = “Your Name”;
                         break;
                     }
                 default:
                     {
                         studentName = “No student found”;
                         break;
                     }
             }
             return studentName;
         }
     }

Step 2

In order to host this service in Console application, let’s add a new console application project “StudentHost” to this solution.

Your console application will have reference to:

  •     StudentService class library
  •     System.ServiceModel.

At the start of this WCF Tutorial, we discuss that hosting a WCF service requires a Managed Process (i.e. console application), Service Host (an instance of ServiceHost class) and one or more Service Endpoints. Detailed implementation of Student host application is as follows:

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost studentServiceHost = null;
            try
            {
                //Base Address for StudentService
                Uri httpBaseAddress = new Uri(“http://localhost:4321/StudentService”);
               
                //Instantiate ServiceHost
                studentServiceHost = new ServiceHost(typeof(StudentService.StudentService),
httpBaseAddress);
 
               //Add Endpoint to Host
                studentServiceHost.AddServiceEndpoint(typeof(StudentService.IStudentService),
                                                        new WSHttpBinding(), “”);           
 
               //Metadata Exchange
                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpGetEnabled = true;
                studentServiceHost.Description.Behaviors.Add(serviceBehavior);
 
                //Open
                studentServiceHost.Open();
                Console.WriteLine(“Service is live now at : {0}”, httpBaseAddress);
                Console.ReadKey();               
            }
            catch (Exception ex)
            {
                studentServiceHost = null;
                Console.WriteLine(“There is an issue with StudentService” + ex.Message);
            }
        }
    }

Now, simply build the console application and run it after setting as startup project. You will see the following screen that shows our self-hosted WCF Service is running.

HostForLIFE.eu WCF with Free ASP.NET Hosting
Try our
WCF 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.



OWIN & Katana.NET Hosting - HostForLIFE.eu :: How to Build a Simple Server using OWIN and Katana

clock April 10, 2015 07:39 by author Rebecca

This article will show you how easy to build a simple server using OWIN and Katana Project. Usually, you use HTML, JavaScript, and CSS files over HTTP from a .NET desktop application to run the scenario code that you've created. But, Katana makes it easier to run you scenario code.

Here is an example using a console application:

First, use NuGet to install a couple packages into the project.

install-package Microsoft.Owin.StaticFiles
install-package Microsoft.Owin.SelfHost

The source for the entire application is 17 lines of code, including statements:

using System;
using Microsoft.Owin.Hosting;
using Owin;
 
namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://localhost:8080";
            WebApp.Start(url, builder => builder.UseFileServer(enableDirectoryBrowsing:true));          
            Console.WriteLine("Listening at " + url);
            Console.ReadLine();
        }
    }
}

Then, the FileServer middleware will serve files from the same directory as the executable.

But, if you don’t want to use the default location, you can provide your own IFileSystem and serve files from anywhere. Katana currently provides two implementations of IFileSystem – one to serve embedded resources and the other one serve files from the physical file system. You can construct a PhysicalFileSystem for an arbitrary location on the hard drive, like this following code below:

static void Main(string[] args)
{
    var url = "http://localhost:8080";
    var root = args.Length > 0 ? args[0] : ".";
    var fileSystem = new PhysicalFileSystem(root);
 
    var options = new FileServerOptions
    {
        EnableDirectoryBrowsing = true,
        FileSystem = fileSystem                           
    };
 
    WebApp.Start(url, builder => builder.UseFileServer(options));          
    Console.WriteLine("Listening at " + url);
    Console.ReadLine();
}

The FileServer middleware is actually a composite wrapper around three other pieces of middleware:

  • DefaultFiles (to select a default.html file, if present, when a request arrives for a directory).
  • DirectoryBrowser (to list the contents of a directory if no default file is found).
  • StaticFile (to reply with the contents of a file in the file system).

All three pieces of middleware are configurable through the UseFileServer extension method.

For example, the static file middleware will only serve files with a known content type. Although the list of known content types is extensive, you might need to serve files with uncommon extensions, in which case you can plug a custom IContentTypeProvider into the static files middleware.

public class CustomContentTypeProvider : FileExtensionContentTypeProvider
{
    public CustomContentTypeProvider()
    {
        Mappings.Add(".nupkg", "application/zip");
    }
}


Now the final program looks like the following:

static void Main(string[] args)
{
    var url = "http://localhost:8080";
    var root = args.Length > 0 ? args[0] : ".";
    var fileSystem = new PhysicalFileSystem(root);
    var options = new FileServerOptions();
    
    options.EnableDirectoryBrowsing = true;
    options.FileSystem = fileSystem;       
    options.StaticFileOptions.ContentTypeProvider = new CustomContentTypeProvider();
 
    WebApp.Start(url, builder => builder.UseFileServer(options));          
    Console.WriteLine("Listening at " + url);
    Console.ReadLine();
}

HostForLIFE.eu OWIN and Katana.NET 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.



WCF Hosting - HostForLIFE.eu :: Simple Steps to Enable Tracing in WCF

clock April 7, 2015 11:47 by author Rebecca

Tracing mechanism in Windows Communication Foundation is based on the classes that resides in System.Diagnostic namespace. Important classes are Trace, TraceSource and TraceListener. For better understanding, i'm gonna explain to you step by step approach in this WCF Tutorial.

Follow these steps to enable tracing in WCF:

Step 1: Configuring WCF to emit tracing information/Define Trace Source

You will have the following options:

  1.     System.ServiceModel
  2.     System.ServiceModel.MessageLogging
  3.     System.ServiceModel.IdentityModel
  4.     System.ServiceModel.Activation
  5.     System.Runtime.Serialization
  6.     System.IO.Log
  7.     Cardspace

In configuration file, you need define a source to enable this configuration as follows:

<source name=”System.ServiceModel.MessageLogging”>

Step 2: Setting Tracing Level

We have the following available options:

  •     Off
  •     Critical
  •     Error
  •     Warning
  •     Information
  •     Verbose
  •     ActivityTracing
  •     All

And we need to set this tracing level to available options other than default OFF.

In configuration file, we can choose above values for switchValue attribute as follows:

<source name=”System.ServiceModel.MessageLogging”
switchValue=”Information”>

Step 3: Configuring a Trace Listener

For configuring a trace listener, we will add following to config file:

           <listeners>
<add name=”messages”
type=”System.Diagnostics.XmlWriterTraceListener”
initializeData=”d:logsmessages.svclog” />
</listeners>

Step 4: Enabling Message Logging

Follow this code below to enable message logging:

<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage=”true”
logMalformedMessages=”false”
logMessagesAtServiceLevel=”true”
logMessagesAtTransportLevel=”false”
maxMessagesToLog=”3000″
maxSizeOfMessageToLog=”2000″/>
</diagnostics>
</system.serviceModel>

NOTES:

logEntireMessage: By default, only the message header is logged but if we set it to true, entire message including message header as well as body will be logged.
logMalformedMessages: this option log messages those are rejected by WCF stack at any stage are known as malformed messages.
logMessagesAtServiceLevel: messages those are about to enter or leave user code.
logMessagesAtTransportLevel: messages those are about to encode or decode.
maxMessagesToLog: maximum quota for messages. Default value is 10000.
maxSizeOfMessageToLog: message size in bytes.

If you put all of the steps together, configuration file will appear like this:

<system.diagnostics>
    <sources>
      <source name=”System.ServiceModel.MessageLogging”>
        <listeners>
          <add name=”messagelistener”
               type=”System.Diagnostics.XmlWriterTraceListener” initializeData=”d:logsmyMessages.svclog”></add>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
    <system.serviceModel>
      <diagnostics>
        <messageLogging logEntireMessage=”true”
                        logMessagesAtServiceLevel=”false”
                        logMessagesAtTransportLevel=”false”
                        logMalformedMessages=”true”
                        maxMessagesToLog=”5000″
                        maxSizeOfMessageToLog=”2000″>
        </messageLogging>
      </diagnostics>
    </system.serviceModel>

In this case, information will be buffered and not published to file automatically, So, we can set the autoflush property of the trace under sources as follows:

autoflush =”true” />

HostForLIFE.eu WCF 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