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 Identify Unused Indexes in SQL Server

clock May 18, 2015 07:44 by author Rebecca

Indexes play an important role in SQL Server performance. Coins always have two sides, just like a well-designed index can improve query performance and an incorrect index can impact query performance. So it is important to find which indexes are not being used. It helps us to reduce storage and reduce the overhead of the database engine to maintain unused indexes. But how can we find indexes that are not being used? In this article, I'm gonna tell you how to identify unused indexes in SQL Server.

The absence of an index can result in table or index scans that reduce performance in some case and also too many indexes require extra storage and extra effort to maintain the database and it might slow down insert / update operations. One of the approaches to improve the overall performance is keep used indexes but drop all unused indexes.

"dm_db_index_physical_stats" is a dynamic management view related to index statistics. This view gives information about indexes used or unused, it complete or missing some columns is irrelevant. This dynamic view has many important columns like user_seeks (number of seeks by user queries), user_scans (number of scans by user queries), user_lookups (number of bookmark lookups by user queries) and a combination of these three columns provide us a total read count. The column user updates (number of updates by user queries) indicates the level of maintenance on the index caused by insert / update / delete operations on the table or view. A proper join among these DVM and system tables such as indexes, objects and schemas enable us to list all unused indexes for a single database.

The following query helps us to find unused indexes in our database:

    SELECT  
    o.name AS TableName, 
    i.name AS Indexname, 
    i.is_primary_key AS PrimaryKey, 
    s.user_seeks + s.user_scans + s.user_lookups AS NumOfReads, 
    s.user_updates AS NumOfWrites, 
    (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = s.index_id AND s.object_id = p.object_id) AS TableRows, 
    'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(c.name) + '.' + QUOTENAME(OBJECT_NAME(s.object_id)) AS 'DropStatement' 
    FROM sys.dm_db_index_usage_stats s  
    INNER JOIN sys.indexes i ON i.index_id = s.index_id AND s.object_id = i.object_id  
    INNER JOIN sys.objects o ON s.object_id = o.object_id 
    INNER JOIN sys.schemAS c ON o.schema_id = c.schema_id 
    WHERE OBJECTPROPERTY(s.object_id,'IsUserTable') = 1 
    AND s.databASe_id = DB_ID()  
    AND i.type_desc = 'NONCLUSTERED' 
    AND i.is_primary_key = 0 
    AND i.is_unique_constraint = 0 

The preceding query includes the following helpful information.

  •     Table name
  •     Index name
  •     Primary key
  •     Number of read count
  •     Number of writes
  •     Total number of rows
  •     Drop statement

The following  is the output of the preceding query:

After running the preceding query for the database it will list all the non-clustered indexes for all tables. Now we can determine the unused indexes by comparing the number of reads applied to an index with the number of writes. If we have a number of reads (NumOfReads column in the preceding query) then the indexes are not being used.

Base on the query result and application knowledge, we may decide which index needs to be dropped and the last column of the query contains a drop index statement.

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.



SQL Server 2014 with Free ASP.NET Hosting - HostForLIFE.eu :: Import Excel File into SQL Server using SQLBULK in ASP.NET

clock May 18, 2015 06:17 by author Peter

Today, I will show you how to upload excel file, read Excel file data,  save Excel file data & import into SQL Server using SQLBULK in ASP.NET.

First step, you must create the excel file. And then create a SQL table in database like the following picture:

Next step, add the code in "Default.aspx"

<asp:FileUpload ID="fupUpload" runat="server" />
<asp:Button ID="btnImport" Font-Bold="true" ForeColor="White"
BackColor="#136671" Height="23px" runat="server" Text="Import Excel Data"
onclick="btnImport_Click" />


Now, write the following code in "Default.aspx.cs"
Add these NameSpace
using System.IO;
using System.Data.OleDb;
using System.Data;


Write the code in Click Event of Import Button:
protected void btnImport_Click(object sender, EventArgs e)
{
 string strFilepPath;
 DataSet ds = new DataSet();
 string strConnection = ConfigurationManager.ConnectionStrings
                          ["connectionString"].ConnectionString;
 if (fupUpload.HasFile)
 {
  try
  {
    FileInfo fi = new FileInfo(fupUpload.PostedFile.FileName);
    string ext = fi.Extension;
    if (ext == ".xls" || ext == ".xlsx")
    {
     string filename = Path.GetFullPath(fupUpload.PostedFile.FileName);
     string DirectoryPath = Server.MapPath("~/UploadExcelFile//");
     strFilepPath = DirectoryPath + fupUpload.FileName;     
     Directory.CreateDirectory(DirectoryPath);
     fupUpload.SaveAs(strFilepPath);  
     string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                      + strFilepPath + ";Extended Properties=\"Excel 12.0
                      Xml;HDR=YES;IMEX=1\"";
     OleDbConnection conn = new OleDbConnection(strConn);
     conn.Open();    
     OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
     OleDbDataAdapter da = new OleDbDataAdapter(cmd);
     da.Fill(ds);
     DeleteExcelFile(fupUpload.FileName); // Delete File Log
     SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection,
                                   SqlBulkCopyOptions.KeepIdentity);
     sqlBulk.DestinationTableName = "Table_1";
     sqlBulk.WriteToServer(ds.Tables[0]);
     conn.Close();
     sqlBulk.Close();     
     ScriptManager.RegisterStartupScript(Page, GetType(), "script1", 
        "alert('Excel file successfully imported into DB');", true);
     return;
    }    
    else
    {
      ScriptManager.RegisterStartupScript(Page, GetType(), "script1",  
                    "alert('Please upload excel file only');", true);
     return;
    }
  }  
  catch (Exception ex)
   {
    DeleteExcelFile(fupUpload.FileName);      
    ScriptManager.RegisterStartupScript(Page, GetType(), "script1",  
      "alert('error occured: " + ex.Message.ToString() + "');", true);
    return;
   }
  } 
 else
  {
    ScriptManager.RegisterStartupScript(Page, GetType(), "script1",  
                        "alert('Please upload excel file');", true);
   return;
  }
}
protected void DeleteExcelFile(string Name)
{             
 if (Directory.Exists(Request.PhysicalApplicationPath +  
                                           "UploadExcelFile\\"))
   {     
    string[] logList = Directory.GetFiles(Request.PhysicalApplicationPath
                       + "UploadExcelFile\\", "*.xls");
     foreach (string log in logList)
      {        
        FileInfo logInfo = new FileInfo(log);
        string logInfoName = logInfo.Name.Substring(0, 
                             logInfo.Name.LastIndexOf('.'));
        if (logInfoName.Length >= Name.Length)
         {           
          if (Name.Equals(logInfoName.Substring(0, Name.Length)))
           {
             logInfo.Delete();
           }
         }
      }
   }
}

I hope it works for you! Good luck.

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.



SQL Server 2014 with free ASP.NET Hosting - HostForLIFE.eu :: How to Use RAND() Function in SQL Server 2014

clock May 15, 2015 07:01 by author Rebecca

You know that RAND() function in SQL Server generates a random float value 0 through 1 (excluding 0 and 1). In this article, I will show you how to generate different random number for each group using RAND() Function.

First, let's us create the following dataset:

CREATE TABLE #random(no INT)
INSERT INTO #random(no)
SELECT 1 UNION ALL
SELECT 1 UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 3


If you want to generate a random value, you can use the following code:

SELECT no, RAND() AS random_number FROM #random

This code will result to:
no random_number
 1 0.370366365964781
 1 0.370366365964781
 1 0.370366365964781
 2 0.370366365964781
 3 0.370366365964781
 3 0.370366365964781

Please note that when you execute it , you may get different random number than what I got for column 2 but all will be same. What if you want to generate random number in such a way that it is reset to each column value (in this case the column is no)? Did you know that RAND() accepts a seed value as well?

If you execute the following code:

SELECT no, RAND() AS random_number,RAND(no) AS random_number_reset FROM #random

Then, it will comes to the result:
no random_number random_number_reset
 1 0.58334760467751 0.713591993212924
 1 0.58334760467751 0.713591993212924
 1 0.58334760467751 0.713591993212924
 2 0.58334760467751 0.713610626184182
 3 0.58334760467751 0.71362925915544
 3 0.58334760467751 0.71362925915544


Please note that when you execute it , you may get different random number than what I got for column2 2 and 3. If you notice the result the values of second column is same for all rows, whereas the values of third column is same withing a group (column no), and different across groups. So if you want to generate random number differently for each group, you can make use of this method.

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.



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.



SQL Server 2014 with Free ASP.NET Hosting - HostForLIFE.eu :: How to encrypt/decrypt string in SQL Server ?

clock April 21, 2015 07:36 by author Peter

In this tutorial, I will show you how to  to encrypt/decrypt string in SQL Server. First step, you must write the following DB Script:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:   <Description,,>
-- =============================================
ALTER PROCEDURE Enc_Dec
    @username varchar(20),
      @password varchar(10)
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @encrypt_val VARBINARY(200)
    SELECT @encrypt_val = EncryptByPassPhrase('xxx', @password)
    SELECT @encrypt_val
    INSERT INTO reg_users (username,r_pwd)VALUES(@username ,CONVERT(VARCHAR(200), @encrypt_val, 1))
    SELECT CONVERT(VARCHAR(200),DecryptByPassPhrase('xxx', @encrypt_val ))
END
GO

The output of the above code as shown in the following picture:

 

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.



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