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 5 Hosting Italy - HostForLIFE.eu :: Create Custom Configuration Sections in ASP.NET 5

clock February 2, 2015 07:10 by author Peter

In this article, I will explain you about creating a custom configuration sections in ASP.NET 5. We want to extend ASP.NET configuration settings using XML configuration elements of your own. To do this, we produce a custom configuration section handler. The handler should be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are outlined in XML configuration elements in a specific section of a web.config file. We willl browse and write these settings through the handler's properties. And here is the code that I used:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
           {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

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 - Belgium :: Filter and Sorting in GridView using DataView in ASP.NET 5

clock January 30, 2015 05:50 by author Peter

In this article i will explain you how to Filter and Sorting in GridView using DataView in ASP.NET 5. First, you must create a new project and write the below code in ASP.NET:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Filter and Sorting in GridView using DataView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Enter ID:
               </td>
                <td>
                    <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Enter User Name:
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSearch" runat="server" Text="Search"
                        onclick="btnSearch_Click"></asp:Button>
                </td>
            </tr>
        </table>
        <asp:GridView ID="GridFilter" runat="server" BackColor="White" BorderColor="#CC9966"
            AllowPaging="True" PageSize="5" BorderStyle="Solid" AutoGenerateColumns="False"
            BorderWidth="1px" CellPadding="4" Font-Names="Georgia" DataKeyNames="User_ID"
            Font-Size="Small" OnSorting="GridFilter_Sorting" AllowSorting="true">
            <Columns>
                <asp:BoundField DataField="User_ID" HeaderText="User_ID" SortExpression="User_ID" />       <asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
                <asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            </Columns>
            <FooterStyle BackColor="Tan" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C#
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;
using System.Configuration;
public partial class GridRowFilter : System.Web.UI.Page
{
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
        {
            GridFilter.DataSource = BindUsers();
            GridFilter.DataBind();
        }
    }
    private DataSet BindUsers()
    {
        ds = new DataSet();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        return ds;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            ds = BindUsers();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dvData = dt.DefaultView;
            string strFilter = " 1=1 ";
            if (!string.IsNullOrEmpty(txtId.Text))
                strFilter = strFilter + " And User_ID = " + Convert.ToInt32(txtId.Text);
            if (!string.IsNullOrEmpty(txtUserName.Text))
                strFilter = strFilter + " And UserName Like '%" + txtUserName.Text + "%'";            dvData.RowFilter = strFilter;
            GridFilter.DataSource = dvData;
            GridFilter.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void GridFilter_Sorting(object sender,GridViewSortEventArgs e)
    {
        try
        {
            DataSet ds = BindUsers();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dvData = dt.DefaultView;
            if (ViewState["SortDirection"] != null && ViewState["SortDirection"].ToString() != "")
                dvData.Sort = e.SortExpression + " " + ConvertSortDirection(ViewState["SortDirection"].ToString());
            else
                dvData.Sort = e.SortExpression + " " + ConvertSortDirection("ASC");
            GridFilter.DataSource = dvData;
            GridFilter.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;        }
    }
    private string ConvertSortDirection(string sortDireciton)
    {
        try
        {
            if (sortDireciton != null)
            {
                switch (sortDireciton)
                {
                    case "ASC":
                        ViewState["SortDirection"] = "DESC";
                        break;
                    case "DESC":
                        ViewState["SortDirection"] = "ASC";
                        break;
                }
            }
            return sortDireciton;
        }
        catch (Exception err)
        {
            throw err;
        }
    }
}

In VB.NET
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class GridRowFilter
    Inherits System.Web.UI.Page
    Private ds As DataSet
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            GridFilter.DataSource = BindUsers()
            GridFilter.DataBind()
        End If
    End Sub
    Private Function BindUsers() As DataSet
        ds = New DataSet()
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)        Dim cmd As New SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con)        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
        Return ds
    End Function
   Protected Sub btnSearch_Click(sender As Object, e As EventArgs)
        Try
            ds = BindUsers()
            Dim dt As New DataTable()
            dt = ds.Tables(0)
            Dim dvData As DataView = dt.DefaultView
            Dim strFilter As String = " 1=1 "
            If Not String.IsNullOrEmpty(txtId.Text) Then
                strFilter = strFilter & " And User_ID = " & Convert.ToInt32(txtId.Text)
            End If
            If Not String.IsNullOrEmpty(txtUserName.Text) Then
                strFilter = (strFilter & " And UserName Like '%") + txtUserName.Text & "%'"
            End If
            dvData.RowFilter = strFilter
            GridFilter.DataSource = dvData
            GridFilter.DataBind()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Protected Sub GridFilter_Sorting(sender As Object, e As GridViewSortEventArgs)
        Try
            Dim ds As DataSet = BindUsers()
            Dim dt As New DataTable()
            dt = ds.Tables(0)
            Dim dvData As DataView = dt.DefaultView
            If ViewState("SortDirection") IsNot Nothing AndAlso ViewState("SortDirection").ToString() <> "" Then
                dvData.Sort = e.SortExpression & " " & ConvertSortDirection(ViewState("SortDirection").ToString())
            Else
                dvData.Sort = e.SortExpression & " " & ConvertSortDirection("ASC")
            End If
            GridFilter.DataSource = dvData
            GridFilter.DataBind()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
   Private Function ConvertSortDirection(sortDireciton As String) As String
        Try
            If sortDireciton IsNot Nothing Then
                Select Case sortDireciton
                    Case "ASC"
                        ViewState("SortDirection") = "DESC"
                        Exit Select
                    Case "DESC"
                        ViewState("SortDirection") = "ASC"
                        Exit Select
                End Select
            End If
            Return sotDireciton
        Catch err As Exception
            Throw err
       End Try
    End Function
End Class

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 Germany - HostForLIFE.eu :: Create Validation Control Error Messages with Alert Box in ASP.NET 5

clock January 26, 2015 06:23 by author Peter

At this short article, we will Create validation control's Error messages in Alert box in ASP.NET 5. First step, you need to know about how to show validation control's Error messages in Alert box in ASP.NET. Then, write the following code:

 

ASP.NET
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to show validation control's Error messages in Alert box in ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" ValidationGroup="Validation"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
                    Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblGender" runat="server" Text="Gender"></asp:Label>
            </td>
            <td>
                <asp:DropDownList ID="ddlGender" runat="server" ValidationGroup="Validation">
                    <asp:ListItem Selected="True" Value="0">--Select--</asp:ListItem>
                    <asp:ListItem Value="1">Male</asp:ListItem>
                    <asp:ListItem Value="2">Female</asp:ListItem>
                </asp:DropDownList>
                <asp:CompareValidator ID="CVGender" runat="server" ControlToValidate="ddlGender"
                    Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
                    ValueToCompare="0"></asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblEmail" runat="server" Text="Email Address"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" ValidationGroup="Validation"></asp:TextBox>
                <asp:RegularExpressionValidator ID="regEmail" runat="server" ControlToValidate="txtEmail"
                    Display="None" ValidationGroup="Validation" ErrorMessage="Enter Valid Email address "
                    ValidationExpression="^([a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]){1,70}$">
                </asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblValidation" runat="server" Text="* Marked fields are mandatory"
                    ForeColor="Red"></asp:Label>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnShowAlert" runat="server" Text="Show Alert" ValidationGroup="Validation" />
                <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
                    ShowSummary="False" ValidationGroup="Validation" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

And here is the result:

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 Germany - HostForLIFE.eu :: Create DropDownList Validation with JQuery JavaScript In ASP.NET

clock January 19, 2015 07:19 by author Peter

This article will explain you how Create DropDownList Validation with JQuery JavaScript in ASP.NET 5 where DropDown is either bind with SqlDataSource or listItems. Place one drop down and button on the page in design view and add JQuery javascript file in solution and add it's reference in head section of page. Then, Write following JQuery script in head section of page.

<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script> 
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#Button1').on('click', function(e) {
var selectedText = $('#DropDownList1    
option:selected').text().toLowerCase();
if (selectedText == 'select')
{
alert('Please select any language.');
e.preventDefault();
 }
else
alert('You selected ' + selectedText);
       })        
 })
</script>
</head>


HTML Code for Drop Down And Button
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>C#</asp:ListItem>
<asp:ListItem>VB</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />

Now if DropDownList is obtaining populated from database by SqlDataSource then we'd like to line AppendDataBoundItems property of dropdown to true and add one list item with text choose at 0th index in Page_Load event.
<asp:DropDownList ID="DropDownList2" runat="server"
AppendDataBoundItems="True"
DataSourceID="SqlDataSource1"
DataTextField="ProductName"
DataValueField="ProductID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDbConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Products]">
</asp:SqlDataSource>   
<asp:Button ID="Button2" runat="server" Text="Button" />


Next step, write the following code in code behind.
protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList2.Items.Add(new ListItem("select", "0"));
    }

Then write following JQuery code in head section of html source of page.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#Button2').on('click', function(e) {
var selectedValue = $('#DropDownList2').val();
if (selectedValue == 0)
{
alert('Please select any product.');
e.preventDefault();
}
else
alert('you selected product with ID ' + selectedValue);
})
})
</script>

If you wanna use the JavaScript code Instead of Jquery then write the following code:
<script type="text/javascript">
function Validation() {
var selectedValue =       document.getElementById('<%=DropDownList2.ClientID%>').value;
if (selectedValue == "0")
{
alert("Please Select Product");
 }
else {
alert("You selected " + selectedValue);
 }
}
</script>

Finally, Call the function bellow in OnClientClick Event of button:
<asp:Button ID="Button2" runat="server" Text="Button" OnClientClick="Validation>

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 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 Spain - HostForLIFE.eu :: Sending Data to Another Page Using jQuery with QueryString in ASP.NET 5

clock January 12, 2015 06:37 by author Administrator

With this article, I will tell you about sending data to another page using jQuery with QueryString in ASP.NET 5. The page PassDataJQueryQueryString.aspx (Source Page), this is the page from where we want to send the data (value). The page consists of an TextBox for Name ,TextBox for Qualification and DropDownList for Technology whose values we need to send to the other page ( In this tutorial I named it: DestinationPage.aspx).

Source Page(PassDataJQueryQueryString.aspx)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Sending Data to Another Page Using jQuery with QueryString in ASP.NET 5</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnSubmit").click(function () {
                var url = "DestinationPage.aspx?name=" + encodeURIComponent($("#txtName").val()) + "&Qualification=" + encodeURIComponent($("#txtQualification").val()) + "&technology=" + encodeURIComponent($("#ddlTechnology").val());
                window.location.href = url;
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Qualification
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="txtQualification" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Technology
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:DropDownList ID="ddlTechnology" runat="server">
                        <asp:ListItem Value=".NET" Text=".NET">
                        </asp:ListItem>
                        <asp:ListItem Value="Java" Text="Java">
                        </asp:ListItem>
                        <asp:ListItem Value="PHP" Text="PHP">
                        </asp:ListItem>
                        <asp:ListItem Value="SAP" Text="SAP">
                        </asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Destination Page(DestinationPage.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        var getData = new Array();
        $(function () {
            if (getData.length == 0) {
                if (window.location.search.split('?').length > 1) {
                    var params = window.location.search.split('?')[1].split('&');
                    for (var i = 0; i < params.length; i++) {
                        var key = params[i].split('=')[0];
                        var value = decodeURIComponent(params[i].split('=')[1]);
                        getData [key] = value;
                    }
                }
            }
            if (getData["name"] != null && getData["Qualification"] != null && getData["technology"] != null) {
                var data = "<u>Values in Previous Page</u><br /><br />";
                var name;
                name = getData["name"];
                $("#lblName").html(name);
                var qualification;
                qualification = getData["Qualification"];
                $("#lblQualification").html(qualification);
                var technology;
                technology = getData["technology"];
                $("#lblTechnology").html(technology);
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:Label ID="lblName" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    Qualification
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:Label ID="lblQualification" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    Technology
                </td>
               <td>
                    :
                </td>
                <td>
                    <asp:Label ID="lblTechnology" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

And this is the output:



ASP.NET 5 Hosting Italy - HostForLIFE.eu :: How to Create ImageButton Control in ASP.NET ?

clock January 9, 2015 05:35 by author Peter

With this post, I will tell you how to create ImageButton Control in ASP.NET 5. First, you need to declare ASP.NET ImageButton Control. Declare the ImageButton by the below code with property,As like Alternative text, ImageUrl,Height,Width.Image Button is predefined Asp.net web control Use in web development.

Declare ImageButton by fallowing code with property,As like Alternative text, ImageUrl,Height,Width.Image Button is predefined Asp.net web control Use in web development.
And here is the code:
<asp:ImageButton id="imagebutton1" runat="server"
    AlternateText="ImageButton 1"
    ImageAlign="left"
    ImageUrl="~/Images/image1.jpg"
    OnClick="ImageButton_Click" Height="148px" Width="274px"/>

For Access ImageButton by javascript we  use following code:
<script language="C#" runat="server">
  void ImageButton_Click(object sender, ImageClickEventArgs e)
      {
         Label1.Text = "You clicked ImageButton control at the coordinates: (" +
                       e.X.ToString() + ", " + e.Y.ToString() + ")";
      }
   </script>

The JavaScript code we get clicked position in Image.and print this on the Label Text.

Code of ASP.NET Image Control:
<%@ Page Language="C#" AutoEventWireup="True" %>
<!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>
    <title>ImageButton Sample</title>
<script language="C#" runat="server">
      void ImageButton_Click(object sender, ImageClickEventArgs e)
      {
         Label1.Text = "You clicked ImageButton control at the coordinates: (" +
                       e.X.ToString() + ", " + e.Y.ToString() + ")";
      }
  </script>
</head>
<body style="height: 261px">
   <form id="form1" runat="server">
      <h3>ImageButton Example:</h3>
      Click Anywhere on the image.<br /><br />
      <asp:ImageButton id="imagebutton1" runat="server"
           AlternateText="ImageButton 1"
           ImageAlign="left"
           ImageUrl="~/Images/Image1.jpg"
           OnClick="ImageButton_Click" Height="148px" Width="274px"/>
      <br />
      <br />
      <br />
      <asp:label id="Label1" runat="server"/>
      <br />
   </form>
</body>
</html>

Finally, this is the result:



ASP.NET 5 Hosting Russia - HostForLIFE.eu :: How to Preview Image Before Upload with jQuery in ASP.NET ?

clock January 5, 2015 05:13 by author Peter

With this article, I will explain you how to preview image before upload with jQuery using FileUpload in ASP.NET 5. While for the browsers that support HTML5 i.e. Internet Explorer, Mozilla FireFox, Google Chrome and Opera, the image preview will display usingHTML5 FileReader API. Preview image before upload using FileUpload control and jQuery in ASP.NET.

Method 1:
In this method 1, we will use the code below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Preview image before upload using FileUpload control and jQuery in ASP.NET </title>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function PreviewImageBeforeUpload(Imagepath) {
            if (Imagepath.files && Imagepath.files[0]) {
                var Filerdr = new FileReader();
                Filerdr.onload = function (e) {
                    $('#ImagePreview').attr('src', e.target.result);
                }
                Filerdr.readAsDataURL(Imagepath.files[0]);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FilePreview" runat="server" onchange="PreviewImageBeforeUpload(this);" />
        <br />
        <asp:Image ID="ImagePreview" runat="server" Width="150px" Height="150px" />
        <asp:Button ID="btnSubmit" runat="server" Text="Upload" />
    </div>
    </form>
</body>
</html>

Next, Method 2 will using the DXImageTransform filter CSS property in browsers that don’t support HTML5 i.e. Internet Explorer 8 and 9.

Method 2:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Preview image before upload using FileUpload control and jQuery in ASP.NET
    </title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $("#FilePreview").change(function () {
                $("#ImagePreview").html("");
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                if (regex.test($(this).val().toLowerCase())) {
                    if ($.browser.msie && parseFloat(jQuery.browser.version) <= 9.0) {
                        $("#ImagePreview").show();
                        $("#ImagePreview")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $(this).val();
                   }
                    else {

                        $("#ImagePreview").show();
                        $("#ImagePreview").append("<img />");
                        var Filerdr = new FileReader();
                        Filerdr.onload = function (e) {
                            $("#ImagePreview img").attr("src", e.target.result);
                        }
                        Filerdr.readAsDataURL($(this)[0].files[0]);
                    }
                } else {
                    alert("Please upload a valid image file.");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FilePreview" runat="server" />
        <br />
        <div id="ImagePreview" style="width: 150px; height: 150px">
        </div>
        <asp:Button ID="btnSubmit" runat="server" Text="Upload" />
    </div>
    </form>
</body>
</html>



ASP.NET 5 Hosting France - HostForLIFE.eu :: Develop a Captcha Image Generator in ASP.NET

clock December 19, 2014 05:38 by author Peter

In this tutorial, I will explain you how to Develop a Captcha Image Generator in ASP.NET 5 with C# or VB.NET. CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart".  And here is the code that I use to generate take one .aspx page as GenerateCaptcha.aspx :

GenerateCaptcha.aspx.cs:
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public partial class GenerateCaptcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        int height = 40;
        int width = 110;
        Bitmap bmp = new Bitmap(width, height);
        RectangleF rectf = new RectangleF(12, 6, 0, 0);
        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawString(Session["captcha"].ToString(), new Font("Cambria", 13, FontStyle.Bold), Brushes.Red, rectf);
        g.DrawRectangle(new Pen(Color.Green), 1, 1, width - 15, height -10);
        g.Flush();
        Response.ContentType = "image/jpeg";
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
        g.Dispose();
        bmp.Dispose();
    }
}

Take .aspx where you want to use captcha.
UseCaptcha.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create your own captcha image generator in ASP.NET using C#.NET/VB.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <table>
                    <tr>
                        <td style="height: 50px; width: 100px;">
                            <asp:Image ID="imgCaptcha" runat="server" />
                        </td>
                        <td valign="middle">
                            <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
        </asp:UpdatePanel>
        Enter Captcha:
        <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </div>
    </form>
</body>
</html>

UseCaptcha.aspx.cs
using System.Text;
using System.Drawing.Imaging;
public partial class UseCaptcha : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillCaptcha();
        }
    }
    void FillCaptcha()
    {
        try
            Random random = new Random();
            string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
                captcha.Append(combination[random.Next(combination.Length)]);
            Session["captcha"] = captcha.ToString();
            imgCaptcha.ImageUrl = "GenerateCaptcha.aspx";
        }
        catch
        {
            throw;
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        FillCaptcha();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["captcha"].ToString() != txtCaptcha.Text)
            Response.Write("Enter Valid Captcha Code");      
        FillCaptcha();
    }
}

And this is the result from the code:



ASP.NET 5 Hosting Italy - HostForLIFE.eu :: Using ValidationSummary Control in ASP.NET

clock December 15, 2014 06:01 by author Peter

Today, I will show you how to ValidationSummary Control in ASP.NET 5. ValidationSummary control allow us to display summary of all validation errors. We can display validation errors summary inline of a web page or a message box or both by using ShowMessageBox and ShowSummary property value true or false.

ValidationSummary will display validation messages as bulleted list, 1 paragraph or only list based on DisplayMode. we can set a header text for validation summar. ASP.NET validationsummary control have many properties to design the error messages text as like fore color, back color, border color, border style, border width, theme, skin and after all CSS class.

This ValidationSummary, allow to summarize of all validation error messages from all validators in a single location. This code below will show you how can we display all validation error messages as summary using ValidationSummary control. In this example, I used three text box and make them required field using requiredfieldvalidator control. When user submit form without entering textboxes value, they got a validation error messages summary in one location as bulleted list.

And here is the example ValidationSummaryExample.aspx code:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "Your Country: " +
            TextBox1.Text.ToString() +
            "<br />Region: " +
            TextBox2.Text.ToString() +
            "<br />City: " +
            TextBox3.Text.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ValidationSummary example: how to use ValidationSummary control in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="BlueViolet"></asp:Label>
        <br /><br />
        <asp:Label ID="Label2" runat="server" Text="Country Name" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator1"
             runat="server"
             ControlToValidate="TextBox1"
             ErrorMessage='Input Country!'
             EnableClientScript="true"
             SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br />
        <asp:Label ID="Label3" runat="server" Text="Region Name" AssociatedControlID="TextBox2"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator2"
             runat="server"
             ControlToValidate="TextBox2"
             ErrorMessage='Input Region!'
             EnableClientScript="true"
             SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br />       
        <asp:Label ID="Label4" runat="server" Text="City Name" AssociatedControlID="TextBox3"></asp:Label>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
             ID="RequiredFieldValidator3"
             runat="server"
             ControlToValidate="TextBox3"
            ErrorMessage='Input Region!'
            EnableClientScript="true"
            SetFocusOnError="true"
             Text="*"
             >
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
       <br /><br />
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Following error occurs:" ShowMessageBox="false" DisplayMode="BulletList" ShowSummary="true" />
    </div>
    </form>
</body>
</html>



HostForLIFE.eu Proudly Launches ASP.NET 5 Hosting

clock December 8, 2014 10:06 by author Peter

European leading web hosting provider, HostForLIFE.eu announces the launch of ASP.NET 5  support on the recently released Windows Server 2012 R2.

HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET 5 hosting in our entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET 5 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

According to Microsoft officials, much of the functionality in the ASP.NET 5 release is a new flexible and cross-platform runtime, a new modular HTTP request pipeline, Cloud-ready environment configuration, Unified programming model that combines MVC, Web API, and Web Pages, Ability to see changes without re-building the project, etc.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR) and Seattle (US) 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. The customers can start hosting our ASP.NET 5 site on our environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET  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.

HostForLIFE.eu offers the latest European ASP.NET 5 hosting installation to all our new and existing customers. The customers can simply deploy our ASP.NET 5 website via our world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET 5 Hosting can be viewed here http://hostforlife.eu/European-ASPNET-5-Hosting

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

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



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