European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 4.6 Hosting - HostForLIFE.eu :: Consume JSON REST Service's Response from ASP.NET

clock August 10, 2015 11:53 by author Peter

Representational State Transfer (REST) isn't SOAP based Service and it exposing a public API over the internet to handle CRUD operations on information. REST is targeted on accessing named resources through one consistent interface (URL). REST uses these operations and alternative existing options of the HTTP protocol:

  • GET
  • POST
  • PUT
  • DELETE

From developer's points of view, it's not as easy as handling the object based Module which is supported after we create SOAP URL as reference or create WSDL proxy.
But .NET will have class to deal with JSON restful service. This document will only cover "how to deal JSON response as a Serialized Object for READ/WRITE & convert JSON object into meanful Object".

In order to consumer JSON restful service , we'd like to do follow steps:

  1. produce the restful request URI.
  2. Post URI and get the response from “HttpWebResponse” .
  3. Convert ResponseStreem into Serialized object from “DataContractJsonSerialized” function.
  4. Get the particular results/items from Serialized Object.

This is very generic function which can be used for any rest service to post and get the response and convert in:
public static object MakeRequest(string requestUrl, object JSONRequest, string JSONmethod, string JSONContentType, Type JSONResponseType) { 
try { 
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; 
//WebRequest WR = WebRequest.Create(requestUrl);  
string sb = JsonConvert.SerializeObject(JSONRequest); 
request.Method = JSONmethod; 
// "POST";request.ContentType = JSONContentType; // "application/json";  
Byte[] bt = Encoding.UTF8.GetBytes(sb); 
Stream st = request.GetRequestStream(); 
st.Write(bt, 0, bt.Length); 
st.Close(); 

using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) { 

if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( 
    "Server error (HTTP {0}: {1}).", response.StatusCode, 
response.StatusDescription)); 

// DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));// object objResponse = JsonConvert.DeserializeObject();Stream stream1 = response.GetResponseStream();  
StreamReader sr = new StreamReader(stream1); 
string strsb = sr.ReadToEnd(); 
object objResponse = JsonConvert.DeserializeObject(strsb, JSONResponseType); 

return objResponse; 

} catch (Exception e) { 

Console.WriteLine(e.Message); 
return null; 

HostForLIFE.eu ASP.NET 4.6 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.



European Entity Framework Hosting - UK :: Introduction about Entity Framework 5 and Implement it on MVC

clock August 5, 2015 09:47 by author Scott

In this article, we will introduce the Entity Framework 5.0 Code First approach in MVC applications. The ADO.NET Entity Framework is an Object Relational Mapper (ORM) included with the .NET framework. It basically generates business objects and entities according to the database tables. It provides basic CRUD operations, easily managing relationships among entities with the ability to have an inheritance relationship among entities.

When using the EF we interact with an entity model instead of the application's relational database model. This abstraction allows us to focus on business behavior and the relationships among entities. We use the Entity Framework data context to perform queries. When one of the CRUD operations is invoked, the Entity Framework will generate the necessary SQL to perform the operation.

How to Implement

To create this application we should have a basic knowledge of the DbContext class of theSystem.Data.Entity namespace. We should also be familiar with views because in this article I am not describing views for each action method so you can create a view according to action methods or you can scaffold templates to create a view for Edit, List, Create, Delete and Details.

We need to install the Entity Framework Nuget package in our application. When we install the Entity Framework Nuget package, two references (System.Data.Entity and EntityFramework) are added to our application. Thereafter we can perform CRUD operations using Entity Framework.

How to Use Entity Framework

Whether you have an existing database or not, you can code your own classes and properties (aka Plain Old CLR Objects, or POCOs) that correspond to tables and columns and use them with the Entity Framework without an .edmx file. In this approach the Entity Framework does not leverage any kind of configuration file (.edmx file) to store the database schema, because the mapping API uses these conventions to generate the database schema dynamically at runtime. Currently, the Entity Framework Code First approach does not support mapping to Stored Procedures. The ExecuteSqlCommand() and SqlQuery() methods can be used to execute Stored Procedures.

To understand the Entity Framework Code First Approach, you need to create an MVC application that has two entities, one is Publisher and another is Book. So let's see an example step-by-step. To create your MVC Application, in Visual Studio select "File" -> "New" -> "Project..." then select "MVC 4 Application" then select "Empty Application".

1. Create Modal Classes

We create classes for Publisher and Book under the Models folder, those classes are used as entities and an entities set. These classes will have mapping with a database because we are using the code first approach and these classes will create a table in a database using the DbContext class of Entity Framework. So let's see these classes one by one.
The Publisher class is in the Models folder; that file name is Publisher.cs as in the following:
using System.Collections.Generic;
namespace ExampleCodeFirstApproch.Models
{
    public class Publisher
    {
        public int PublisherId { get; set; }
        public string PublisherName { get; set; }
        public string Address { get; set; }
        public ICollection<book> Books { get; set; }
    }
}</book>


The Book class is in the Models folder; that file name is Book.cs as in the following:

namespace
ExampleCodeFirstApproch.Models

{
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Year { get; set; }
        public int PublisherId { get; set; }
        public Publisher Publisher { get; set; }
    }
}


2. Create Data Access Layer
This part of the article is the heart of the article as well as the code first approach. First of all we need a connection string so we can connect with our database by application. We create a connection in the web.configfile. I provide the connection string name as DbConnectionString, you are free to give any name to it but remember it because we will use it in our context class.

<connectionStrings>
   
<add name="DbConnectionString"
     
connectionString="Data Source=steve-PC;Initial Catalog=CodeFirst;User ID=sa;
      Password=*******" providerName="System.Data.SqlClient" />
</connectionStrings>

We have both classes, Publisher and Book, so now we will create a context class. We create aLibraryContext class under the Models folder, that file name is LibraryContext.cs. This class inherits DbContextso we can use the DbContext class methods using a LibraryContext class object as in the following:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ExampleCodeFirstApproch.Models
{
    public class LibraryContext :DbContext
    {
        public LibraryContext()
            : base("name=DbConnectionString")
        {
        }
        public DbSet<Publisher> Publishers { get; set; }
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {                     
            modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);
            modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);           
            modelBuilder.Entity<Book>().HasKey(b => b.BookId);
            modelBuilder.Entity<Book>().Property(b => b.BookId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);           
            modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
                .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);           
            base.OnModelCreating(modelBuilder);
        }
    }
}

Our LibraryContext class that inherits the DbContext class is ready. The LibraryContext class has a three-part constructor, DbSet properties, and an OnModelCreating method. Let's see each one by one.

Constructor: It is an empty constructor that doesn't have any parameters, in other words it is the default constructor but it inherits the base class single string parameterized constructor. This constructor constructs a new context instance using the given string as the name (as we used) or the connection string for the database to which a connection will be made. Here DbConnectionString is the name of the connection string defined in the web.config file of the application.

public LibraryContext(): base("name=DbConnectionString")
{
}

Property: When developing with the Code First workflow you define a derived DbContext that represents the session with the database and exposes a DbSet for each type in your model. The common case shown in the Code First examples is to have a DbContext with public automatic DbSet properties for the entity types of your model.
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Book> Books { get; set; }


The Dbset property represents an entity set used to perform create, read, update, and delete operations. A non-generic version of DbSet<TEntity> can be used when the type of entity is not known at build time. Here we are using the plural name of the property for an entity, that means your table will be created with this name in the database for that specific entity.

Method: The LibraryContext class has an override OnModelCreating method. This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down. Basically in this method we configure the database table that will be created by a model or a defined relationship among those tables.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{  
   modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);
   modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   modelBuilder.Entity<Book>().HasKey(b => b.BookId);
   modelBuilder.Entity<Book>().Property(b => b.BookId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
         .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);
   base.OnModelCreating(modelBuilder);
}

This method accepts one parameter, an object of DbModelBuilder. This DbModelBuilder class maps POCO classes to database schema. This method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but this can seriously degrade performance. More control over caching is provided through use of theDbModelBuilder and DbContext classes directly.

Configure/Mapping Properties with the Fluent API
The OnModelCreating() method under the LibraryContext class uses the Fluent API to map and configure properties in the table. So let's see each method used in the OnModelCreating() method one by one.

modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
.WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);

3. Create Controller for CRUD Operations

Now we create two controllers, one for Publisher CRUD operations (PublisherController.cs) and another for Book CRUD operations (BookController.cs) under the Controllers folder in the application. So here is the code for each.

The Publisher controller in the file PublisherController.cs in the Controllers folder:
using System.Linq;
using System.Web.Mvc;
using ExampleCodeFirstApproch.Models;
namespace ExampleCodeFirstApproch.Controllers
{
    public class PublisherController : Controller
    {
        LibraryContext objContext;
        public PublisherController()
        {
            objContext = new LibraryContext();
        }
        #region List and Details Publisher
        public ActionResult Index()
        {
            var publishers = objContext.Publishers.ToList();
            return View(publishers);
        }
        public ViewResult Details(int id)
        {
            Publisher publisher =
              objContext.Publishers.Where(x=>x.PublisherId==id).SingleOrDefault();
            return View(publisher);
        }
        #endregion
        #region Create Publisher
        public ActionResult Create()
        {
            return View(new Publisher());
        }
        [HttpPost]
        public ActionResult Create(Publisher publish)
        {
            objContext.Publishers.Add(publish);
            objContext.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion
        #region edit publisher
        public ActionResult Edit(int id)
        {
            Publisher publisher = objContext.Publishers.Where(
              x => x.PublisherId == id).SingleOrDefault();
            return View(publisher);
        }
        [HttpPost]
        public ActionResult Edit(Publisher model)
        {
            Publisher publisher = objContext.Publishers.Where(
              x => x.PublisherId == model.PublisherId).SingleOrDefault();
            if (publisher != null)
            {
                objContext.Entry(publisher).CurrentValues.SetValues(model);
                objContext.SaveChanges();
                return RedirectToAction("Index");
            }             
            return View(model);
        }
       #endregion
        #region Delete Publisher
        public ActionResult Delete(int id)
        {
            Publisher publisher = objContext.Publishers.Find(id);
            //.Where(x => x.PublisherId == id).SingleOrDefault();

            return View(publisher);
        }
        [HttpPost]
        public ActionResult Delete(int id, Publisher model)
        {
           var publisher =
             objContext.Publishers.Where(x => x.PublisherId == id).SingleOrDefault();
           if (publisher != null)
            {
                objContext.Publishers.Remove(publisher);
                objContext.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        #endregion
    }
}

The Book controller in the file BookController.cs in the Controllers folder:
using
System.Linq;
using System.Web.Mvc;
using ExampleCodeFirstApproch.Models;
namespace ExampleCodeFirstApproch.Controllers
{
    public class BookController : Controller
    {
       LibraryContext objContext;
       public BookController()
        {
            objContext = new LibraryContext();
        }
        #region List and Details Book
        public ActionResult Index()
        {
            var books = objContext.Books.ToList();
            return View(books);
        }
        public ViewResult Details(int id)
        {
            Book book = objContext.Books.Where(x=>x.BookId==id).SingleOrDefault();
            return View(book);
        }
        #endregion
        #region Create Publisher
        public ActionResult Create()
        {
            return View(new Book());
        }
        [HttpPost]
        public ActionResult Create(Book book)
        {
            objContext.Books.Add(book);
            objContext.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion
        #region Edit Book
        public ActionResult Edit(int id)
        {
            Book book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();
            return View(book);
        } 
        [HttpPost]
        public ActionResult Edit(Book model)
        {
            Book book = objContext.Books.Where(x => x.BookId == model.BookId).SingleOrDefault();
            if (book != null)
            {
                objContext.Entry(book).CurrentValues.SetValues(model);
                objContext.SaveChanges();
                return RedirectToAction("Index");
            }             
            return View(model);
        }
       #endregion
        #region Delete Book
        public ActionResult Delete(int id)
        {
            Book book = objContext.Books.Find(id);
            return View(book);
        }
        [HttpPost]
        public ActionResult Delete(int id, Publisher model)
        {
           var book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();
           if (book != null)
            {
                objContext.Books.Remove(book);
                objContext.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        #endregion
    }
}


Both Publisher and Book controllers are ready and create a view according to the action method using a scaffold template and you can download a zip folder. Run the application and you get that your tables are created in the database with a relationship.



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Verify if The Remote Files Exist or Not in ASP.NET 5?

clock July 31, 2015 07:43 by author Peter

Hi, In this post let me explain you about how to verify if  the remote files exist or not in ASP.NET 5.  Sometimes we need to verify if a file exists remotely such as javascript or image file.  Suppose you are in server(xxx.com) and you want to check a file in another server(xxxxxx.com) - in this case it will be helpful. And now, write the following code snippet.

Using HTTPWebRequest:
private bool RemoteFileExistsUsingHTTP(string url)
{
try
{
 //Creating the HttpWebRequest
 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
 //Setting the Request method HEAD, you can also use GET too.
  request.Method = "HEAD";

  //Getting the Web Response
  HttpWebResponse response = request.GetResponse() as HttpWebResponse;

  //Returns TURE if the Status code == 200
  return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}


Using WebClient:
private bool RemoteFileExistsUsingClient(string url)
{
bool result = false;
using (WebClient client = new WebClient())
{
try
{
    Stream stream = client.OpenRead(url);
    if (stream != null)
    {
           result = true;
    }
    else
    {
           result = false;
    }
}
catch
{
 result = false;
}
}
return result;
}

Call Method:
RemoteFileExistsUsingHTTP("http://localhost:16868/JavaScript1.js");

Don't confuse here as a result of it absolutely was implemented in 2 ways. continually use HttpWebRequest class over WebClient because of the following reasons:
1. WebClient internally calls HttpWebRequest
2. HttpWebRequest has a lot of options (credential, method) as compared to Webclient

HostForLIFE.eu ASP.NET 5 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.



HostForLIFE.eu Launches nopCommerce 3.60 Hosting

clock July 14, 2015 10:44 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest NopCommerce 3.60 Hosting support

European Recommended Windows and ASP.NET Spotlight Hosting Partner, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the NopCommerce 3.60 hosting technology.

HostForLIFE.eu supports NopCommerce 3.60 hosting on their latest Windows Server and this service is available to all their new and existing customers. nopCommerce 3.60 is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Their easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web hosting. It has everything you need to get started in selling physical and digital goods over the internet.

HostForLIFE.eu Launches nopCommerce 3.60 Hosting

nopCommerce 3.60 is a fully customizable shopping cart. nopCommerce 3.60 provides new clean default theme. The theme features a clean, modern look and a great responsive design. The HTML have been refactored, which will make the theme easier to work with and customize , predefined (default) product attribute values. They are helpful for a store owner when creating new products. So when you add the attribute to a product, you don't have to create the same values again , Base price (PAngV) support added. Required for German/Austrian/Swiss users, “Applied to manufacturers” discount type and Security and performance enhancements.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, London, Paris, Seattle (US) and Frankfurt (Germany) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customer can start hosting their NopCommerce 3.60 site on their environment from as just low €3.00/month only. HostForLIFE.eu is a popular online Windows based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market. Their powerful servers are specially optimized and ensure NopCommerce 3.60 performance.

For more information about this new product, please visit http://hostforlife.eu/European-nopCommerce-36-Hosting



ASP.NET 5 Hosting Russia - HostForLIFE.eu :: How to Create QR Code Generator with ASP.NET 5?

clock July 9, 2015 11:42 by author Peter

In this post, I will explain you about how to create QR Code Generator with ASP.NET 5. Though there are several solutions for QR Code generation in ASP.NET 5, all of it needs referring to third party dlls. however there's a really simple alternative through that we can create a QR code generator in ASP.Net within minutes without relating any third party dlls. Let's produce a ASP.Net web application with a text box, image control and Button with the following code
<asp:TextBox runat="server" ID="txtData"></asp:TextBox> 
   <asp:Button runat="server" ID="btnClickMe" Text="Click Me" OnClick="btnClickMe_Click" /> 
<br /> 
<asp:Image runat="server" ID="ImgQrCode" Height="160" Width="160" /> 

Now, in the button click event, generate the URL for the API with the data entered in the text box and size of the image control and set it to the image control's image URL property. Write the following code:
protected void btnClickMe_Click(object sender, EventArgs e) 

   ImgQrCode.ImageUrl = "https://chart.googleapis.com/chart?   cht=qr&chl=" + WebUtility.HtmlEncode(txtData.Text) + "&choe=UTF-8&chs=" + ImgQrCode.Height.ToString().Replace("px", "") + "x" + ImgQrCode.Width.ToString().Replace("px", ""); 


And here is the output:

I hope this tutorial works for you!

HostForLIFE.eu ASP.NET 5 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.



ASP.NET 5 Hosting Russia - HostForLIFE.eu :: Bind the empty Grid with Header and Footer when no data in GridView

clock July 3, 2015 11:33 by author Peter

In this example, I will tell you how to  Bind the empty Grid with Header and Footer when no data in GridView and binding the grid using XML data and performing CURD operations on XML file.

First create a new project one your Visual Basic Studio and then write the following code:
using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Xml; 
namespace OvidMDSample  

public partial class Home: System.Web.UI.Page  

private const string xmlFilePath = "~/XML/HiddenPagesList.xml"; 
public string domainUrl = HttpContext.Current.Request.Url.Authority; 
protected void Page_Load(object sender, EventArgs e)  

if (!IsPostBack) 

    BindHiddenPages(); 


private void BindHiddenPages()  

DataSet ds = new DataSet(); 
ds.ReadXml(Server.MapPath(xmlFilePath)); 
if (ds != null && ds.HasChanges()) 

    grdHiddenPages.DataSource = ds; 
    grdHiddenPages.DataBind(); 
}  
else  

    DataTable dt = new DataTable(); 
    dt.Columns.Add("ID"); 
    dt.Columns.Add("PageName"); 
    dt.Columns.Add("Description"); 
    dt.Columns.Add("PageUrl"); 
    dt.Columns.Add("Address"); 
    dt.Rows.Add(0, string.Empty, string.Empty, string.Empty); 
    grdHiddenPages.DataSource = dt; 
    grdHiddenPages.DataBind(); 
    grdHiddenPages.Rows[0].Visible = false; 
    // grdHiddenPages.DataBind(); 



HostForLIFE.eu ASP.NET 5 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.



ASP.NET 5 Hosting Russia - HostForLIFE.eu :: Saving the Selected Data of Radio Button List with ASP.NET 5

clock June 30, 2015 08:38 by author Peter

We create some true or false questions so the user can provide their answer and on a button click the solution are going to be saved to a database. Open your Visual Studio and build an empty web site, provide a suitable name (RadioButtonList_demo). In solution explorer you get your empty web site, add a web form and SQL database as in the following

For web Form:
RadioButtonList_demo (your empty website) then right-click then choose Add New Item -> internet type. Name it RadioButtonList_demo.aspx.

For SQL Server database:
RadioButtonList_demo (your empty website) then right-click then choose Add New Item -> SQL Server database. (Add the database within the App_Data_folder.) In Server explorer, click on your database (Database.mdf) then choose Tables ->Add New Table. create the table like this:

This table is for saving the data of the radio button list, I mean in this table we will get the user's answer of true and false questions. Open your RadioButtonList_demo.aspx file from Solution Explorer and start the design of you're application. Here is the code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<style type="text/css"> 
.style1 

width: 211px; 

.style2 

width: 224px; 

.style3 

width: 224px; 
font-weight: bold; 
text-decoration: underline; 

.style4 

width: 211px; 
font-weight: bold; 
text-decoration: underline; 

</style> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 

</div> 
<table style="width:100%;"> 
<tr> 
<td class="style4"> 
    </td> 
<td class="style3"> 
    Please Answer these Questions</td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
     </td> 
<td class="style2"> 
     </td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
    <asp:Label ID="Label7" runat="server"  
        Text="Is Earth is the only planet in the universe??"></asp:Label> 
</td> 
<td class="style2"> 
    <asp:RadioButtonList ID="RadioButtonList1" runat="server" DataTextField="ans"  
        DataValueField="ans"> 
        <asp:ListItem>True</asp:ListItem> 
        <asp:ListItem>False</asp:ListItem> 
    </asp:RadioButtonList> 
</td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
    <asp:Label ID="Label5" runat="server" Text="Is Moon is our Natural Satellite?"></asp:Label> 
</td> 
<td class="style2"> 
    <asp:RadioButtonList ID="RadioButtonList2" runat="server" DataTextField="ans1"  
        DataValueField="ans1"> 
        <asp:ListItem>True</asp:ListItem> 
        <asp:ListItem>False</asp:ListItem> 
    </asp:RadioButtonList> 
</td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
    <asp:Label ID="Label6" runat="server"  
        Text="Earth is having Rings like Saturn have ?"></asp:Label> 
</td> 
<td class="style2"> 
    <asp:RadioButtonList ID="RadioButtonList3" runat="server" DataTextField="ans2"  
        DataValueField="ans2"> 
        <asp:ListItem>True</asp:ListItem> 
        <asp:ListItem>False</asp:ListItem> 
    </asp:RadioButtonList> 
</td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
     </td> 
<td class="style2"> 
     </td> 
<td> 
     </td> 
</tr> 
<tr> 
<td class="style1"> 
     </td> 
<td class="style2"> 
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit your answer" /> 
</td> 
<td> 
    <asp:Label ID="lbmsg" runat="server"></asp:Label> 
</td> 
</tr> 
<tr> 
<td class="style1"> 
     </td> 
<td class="style2"> 
     </td> 
<td> 
     </td> 
</tr> 
</table> 
</form> 
</body> 
</html> 

And here is the output:


Finally open your RadioButtonList_demo.aspx.cs file to write the code, for making the list box like we assume. Here is the code:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.SqlClient; 
public partial class _Default : System.Web.UI.Page 

protected void Page_Load(object sender, EventArgs e) 



protected void Button1_Click(object sender, EventArgs e) 

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"); 
SqlCommand cmd = new SqlCommand("insert into tbl_data (ans,ans1,ans2) values (@ans,@ans1,@ans2)", con); 
cmd.Parameters.AddWithValue("ans", RadioButtonList1.SelectedItem.Text); 
cmd.Parameters.AddWithValue("ans1", RadioButtonList2.SelectedItem.Text); 
cmd.Parameters.AddWithValue("ans2", RadioButtonList3.SelectedItem.Text); 

con.Open(); 
int i = cmd.ExecuteNonQuery(); 
con.Close(); 

if (i != 0) 

lbmsg.Text = "Your Answer Submitted Succesfully"; 
lbmsg.ForeColor = System.Drawing.Color.ForestGreen; 

else 

lbmsg.Text = "Some Problem Occured"; 
lbmsg.ForeColor = System.Drawing.Color.Red;             





Output:

HostForLIFE.eu ASP.NET 5 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.



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Highlight Dates in Calendar with ASP.NET?

clock June 26, 2015 08:48 by author Peter

In this article, I explained how to How to Highlight Dates in Calendar with ASP.NET. First step create new ASP.NET Empty web Application provides it to that means full name. Now, Add new webfrom to your project. Then drag and drop Calendar on your design page. Now. add two properties WeekendDayStyle-BackColor="Yellow", WeekendDayStyle-ForeColor="Black" to your calender control as shown below and run your application.

<asp:Calendar ID="Calendar1" runat="server" 
WeekendDayStyle-BackColor="Yellow" 
WeekendDayStyle-ForeColor="Green" ></asp:Calendar> 

And here is the output:

You can achieve the same by using (OnDayRender event) code as mentioned below. Remove WeekendDayStyle-BackColor="Yellow", WeekendDayStyle-ForeColor="Green" from Calender control.
Here is the .aspx code
<asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar1_DayRender"></asp:Calendar> 

CodeBehind:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) 
{  
if (e.Day.IsWeekend) 

  e.Cell.BackColor = System.Drawing.Color.Yellow; 
  e.Cell.ForeColor = System.Drawing.Color.Green;  



If you wish to spotlight on 'Monday' write the subsequent code in Calendar1_DayRender event. It highlights the the desired day dates.
if (e.Day.Date.DayOfWeek == DayOfWeek.Monday)  

e.Cell.BackColor = System.Drawing.Color.Yellow; 
e.Cell.ForeColor = System.Drawing.Color.Green;  
}

HostForLIFE.eu ASP.NET 5 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.



ASP.NET 5 Hosting - HostForLIFE.eu :: Learn How to Uncover Silent Validation

clock June 22, 2015 07:52 by author Peter

ASP.NET validation is incredibly helpful and permits developers to confirm data is correct before it gets sent to a data store. Validation can run either on the client side or on the server side and each have their advantages and disadvantages. MVC and Webforms handle validation slightly otherwise and i will not get into those differences during this article. Instead, i'd prefer to explain some best practices and suggestions for you once implementing ASP.NET validation.

Bind Validation To HTML elements
To implement validation, you initially add an HTML element to a page, then a validation element points to it HTML part. In MVC, you'd write one thing like this for a model field known as Name.

<div class="editor-field col-md-10"> 
    <div class="col-md-6"> 
        @Html.TextBoxFor(model => model.Name, new { @class = "form-control" }) 
    </div> 
    <div class="col-md-6"> 
        @Html.ValidationMessageFor(model => model.Name) 
    </div> 
</div> 


In Webforms, write the following code:
<asp:DropDownList ID="Name" runat="server" AutoPostBack="true" FriendlyName="Option:" 
AddBlankRowToList="false" DisplayBlankRowText="False" CausesValidation="true"> 
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem> 
<asp:ListItem Selected="True" Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList> 
<asp:CustomValidator ID="valCheck" ControlToValidate="Name" Display="Static" runat="server" ForeColor="red" 
ErrorMessage="Validation Error Message" SetFocusOnError="True" 
OnServerValidate="CheckForAccess" /> 

This ends up in HTML elements with attributes that may enable the client-side validation framework to execute.

Check For Validation Errors On Postback
Whereas validation ought to run on the client-side before the form is submitted to the server, it's still a good observe to see for errors on the server. There are variety of reasons for this, however the most reason should be that the client is an unknown quantity. There are completely different browsers, JavaScript will be disabled, developer tools enable people to change HTML and thus may result in unexpected data being denote. So, check your validation before you start process your type data on the server. And it's as simple as wrapping your server-side logic in a single code block.

MVC
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit(ViewModel model) 

if (ModelState.IsValid()) 

    // your code to process the form 
}  
else 

    ModelState.AddModelError(String.Empty, "Meaningful Error message); 
    return View(model); 

return RedirectToAction("Index"); 


Webforms
protected void Page_Load(object sender, EventArgs e) 

if (IsPostback) 

    if (!IsValid) 
    { 
        // validation failed. Do something 
        return; 
    } 
     
    // do your form processing here because validation is valid 
}  
else  

    // non-postback 

Do one thing useful with your Validation Errors
If you discover that validation errors have gotten through to your server, you would like to capture them and show them to the user. a quick way that I even have found to try and do this is with a loop using the validator collection and look for errors. There are variety of things you will do like add the error messages to the Validation summary box at the top of your form, write to an audit log or build them seem in a dialog box.

foreach (IValidator aValidator in this.Validators) 

if (!aValidator.IsValid) 

    Response.Write("<br />" + aValidator.ErrorMessage); 



Validation is a critical part of form submission and should be used to it's full potential.

HostForLIFE.eu ASP.NET 5 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.

 



ASP.NET Hosting UK - HostForLIFE.eu :: Create the Databound Controls in ASP.NET

clock June 19, 2015 07:00 by author Peter

In this article we'll study about Databound Controls in ASP.NET. Databound controls are used to display data to the end-user inside the web applications and victimisation databound controls permits you to control the info inside the web applications very simply. Databound controls are bound to the DataSource property. Databound controls area unit composite controls that combine other ASP.NET Controls like Text boxes, Radio buttons, Buttons and so on.

Frequently used Databound controls:

  • Repeater
  • DataList
  • GridView
  • List View
  • Form View
  • Repeater

Employee.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataReapterDemo.aspx.cs" Inherits="DataReapterDemo" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html 
xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<style> 
tr { 
height:40px; 

</style> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<center> 
<div style="  border: 2px solid red;text-align: left;border-radius: 2px;Padding-top: 3px;background-color: Lime;width: 500px;border-radius: 8px;font-size: 20px;"> 
<asp:Repeater ID="rp1" runat="server"> 
<HeaderTemplate> 
<table  style="width:500px;padding-top:0px;Background-color:Gold" > 
<tr> 
    <td style="font-size: 26px; 
text-align: center; 
height: 48px;"> 
        <asp:Label ID="lblhdr" runat="server" Text = "Student Profile"></asp:Label> 
    </td> 
</tr> 
</table> 
</HeaderTemplate> 
<ItemTemplate> 
<table style="width:500px;"> 
<tr> 
    <td> 
        <asp:Label ID="lblempid1" runat="server" Text="Employee ID:"></asp:Label> 
    </td> 
    <td> 
        <asp:Label ID="lblempid2" runat="server" Text='<%# Eval("EmpId") %>'> 
        </asp:Label> 
    </td> 
    <td rowspan="5"> 
        <asp:Image ID="img1" runat="server" Width="100px" ImageUrl= ' 
            <%#"~/images/" + Eval("EmpImage")   %>'/> 
        </td> 
    </tr> 
    <tr> 
        <td> 
            <asp:Label ID="lblempname1" runat="server" Text="Employee Name"></asp:Label> 
        </td> 
        <td> 
            <asp:Label ID="lblempname2" runat="server" Text='<%# Eval("EmpName") %>'> 
            </asp:Label> 
        </td> 
    </tr> 
    <tr> 
        <td> 
            <asp:Label  ID="lblempemailId1" runat="server" Text="Employee EmailId"></asp:Label> 
        </td> 
        <td> 
            <asp:Label ID="lblempemailId2" runat="server" Text='<%# Eval("EmpEmailId") %>'> 
            </asp:Label> 
        </td> 
    </tr> 
    <tr> 
        <td> 
            <asp:Label ID="lblempmob1" runat="server" Text="Mobile Number"></asp:Label> 
        </td> 
        <td> 
            <asp:Label ID="lblempmob2" runat="server" Text='<%# Eval("EmpMobileNum") %>'> 
            </asp:Label> 
        </td> 
    </tr> 
    <tr> 
        <td> 
            <asp:Label ID="lblempgen1" runat="server" Text="Gender"></asp:Label> 
        </td> 
        <td> 
            <asp:Label ID="lblempgen2" runat="server" Text='<%# Eval("EmpGender") %>'> 
            </asp:Label> 
        </td> 
    </tr> 
</table> 
</ItemTemplate> 
<FooterTemplate> 
<table> 
    <tr> 
        <td>    
        @Peter
        </td> 
    </tr> 
</table> 
</FooterTemplate> 
</asp:Repeater> 
</div> 
</center> 
</div> 
</form> 
</body> 
</html>  

Employee.aspx.cs

using System;   
using System.Web;   
using System.Web.UI;   
using System.Web.UI.WebControls;   

using System.Data.SqlClient;   
using System.Data;   
using System.Web.Configuration;   

public partial class DataReapterDemo : System.Web.UI.Page   
{   
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);   
protected void Page_Load(object sender, EventArgs e)   
  {   
if (!IsPostBack)   
{   
Bind();   
}    }   

public void Bind()   
{   
SqlCommand cmd = new SqlCommand("select * from Employee where EmpId = 1200",con);   
SqlDataAdapter da = new SqlDataAdapter(cmd);   
DataSet ds = new DataSet();   
da.Fill(ds, "Employee");   
rp1.DataSource = ds.Tables[0];   
rp1.DataBind();   

}   
}    
  

HostForLIFE.eu ASP.NET 5 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

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in