All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NE Hosting - ASPHostPortal.com :: Easy Ways to dynamically update web config file in asp.net?

clock September 30, 2016 19:48 by author Dan

I want to configure my web config connection string in my aspx page. That mean I want to change my web.config file dynamically. User can change the connection string any time without touching the server. For that the below asp.net c# code will help you to change connection string , appsetting information and ect..  in dynamically.

private void SetConfigSettings()
        {
            try
            {
                // App setting settings
                System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

                //APPsetting value change
                System.Configuration.KeyValueConfigurationElement setting = config.AppSettings.Settings["SupportFormat"];
                if (null != setting)
                    config.AppSettings.Settings["SupportFormat"].Value = txtFormat.Text.Trim();

                //APPsetting value change
                System.Configuration.KeyValueConfigurationElement Pathsetting = config.AppSettings.Settings["Path"];
                if (null != Pathsetting)
                    config.AppSettings.Settings["Path"].Value = txtPath.Text.Trim();


                //Connection string changes
                string newConnectionString = "Data Source=" + txtServer.Text + ";Initial Catalog='" + txtDatabaseName.Text.Replace("'", "") + "';User ID=" + txtUserName.Text + ";Password=" + txtPassword.Text + ";Persist Security Info=True;";

                //Configuration openWebConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
                ConnectionStringsSection sections = config.GetSection("connectionStrings") as ConnectionStringsSection;
                if (sections != null)
                {
                    sections.ConnectionStrings["ConString"].ConnectionString = newConnectionString;
                    ConfigurationManager.RefreshSection("ConString");

                }
                config.Save();

                lblMSG.Text = "Updated successfully!!!";
                lblMSG.ForeColor = Color.Green;
            }
            catch (System.Exception exc)
            {
                lblMSG.Text = exc.Message;
                lblMSG.ForeColor = Color.Red;
            }
        }

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: Easy Ways to Create CheckBox Control in ASP.NET

clock September 26, 2016 20:42 by author Dan

CheckBox is an asp.net web server control. checkbox allow web site visitor to select (checked) a true or false condition. so the checkbox control create a checkbox on web forms page which allow user to switch between a true or false state. checkbox Text property create a caption for it. we can left or right align caption by using checkbox TextAlign property.

the checkbox control has many properties that help us to change looks and style such as ForeColor, BorderColor, BackColor, BorderStyle, BorderWidth, CssClass, EnableTheming, Font, Height, SkinID, ToolTip, Width etc.

if we want to determine whether checkbox is checked (selected) then we need to test the checkbox Checked property. checkbox AutoPostBack property value true enable automatic posting to server. checkbox CheckedChanged event raised when someone change the checkbox true or false state. .net developers can write an event handler for CheckedChanged event. using CheckedChanged event we can know the checkbox current state and can perform any task when page post to server.

the following example demonstarte us how to use checkbox control in asp.net. here we create a web form with a Label and two checkbox control. when someone check the first checkbox then the label show a message that he checked first checkbox. the second checkbox programmatically checked when user checked the first checkbox.

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void CheckBox1_CheckChanged(object sender, System.EventArgs e) {

        if (CheckBox1.Checked == true) {
            Label1.Text = "WOW! You are a member of an asp.net user group.";
            Label1.ForeColor = System.Drawing.Color.Green;
        }
        else{
            Label1.Text = "You are not a member of any asp.net user group.";
            Label1.ForeColor = System.Drawing.Color.Crimson;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>How to use CheckBox control in asp.net</title>
    </head>
  
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">     
            How to use CheckBox control
        </h2>     
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label1"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="Crimson"
            Font-Italic="true"
            Font-Size="X-Large"
            Width="350"
            />
        <br /><br />
        <asp:CheckBox
            ID="CheckBox1"
            runat="server"
            Text="Are you an asp.net user group member?"
            OnCheckedChanged="CheckBox1_CheckChanged"
            AutoPostBack="true"
            Font-Names="Serif"
            Font-Size="X-Large"
            />
    </div>
    </form>
</body>
</html>

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Easy Steps to uncompress CSS or Indent CSS Tag in ASP.NET

clock September 16, 2016 23:05 by author Dan

To uncompress CSS or to restore line break and tab or format css back to state before it was compress, then use this utility.

1) Create one empty web application.

2) On Default.aspx add following lines of code. Following line of code will create one text box to input css, button to Indent CSS tag

<h2>
Welcome to My CSS Indenting Application
</h2>
<p>
<asp:TextBox ID="txtCSSInput" runat="server" TextMode="MultiLine" Rows="10" Columns="50"></asp:TextBox>
</p>
<p>
<asp:Button ID="btnIndentCSS" runat="server" Text="Click to Indent CSS"
onclick="btnIndentCSS_Click" />
</p>
<p>
<asp:Label ID="lblDisplayCSS" runat="server" Text=""></asp:Label>
</p>


3) Add following line of code in Code behind (Default.aspx.cs)

protected void btnIndentCSS_Click(object sender, EventArgs e)
{
lblDisplayCSS.Text = txtCSSInput.Text
.Replace(".", "<br/>.")
.Replace("}#", "}<br/>#")
.Replace(";", ";<br/>")
.Replace("{", "{<br/>")
.Replace("}", "}<br/><br/>");
}


That's it and you are done!


Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: Easy step to make custom config section in ASP.NET

clock August 22, 2016 21:45 by author Dan

You can extend ASP.NET configuration settings with XML configuration elements of your own. To do this, you create a custom configuration section handler. The handler must be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a Web.config file. You can read and write these settings through the handler's properties.

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);
                }
            }
        }
    }
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: 7 Ways To Boost Your ASP.NET Performance

clock August 12, 2016 23:59 by author Dan

ASP.NET is a web application server framework that has been designed to make the process of website development easier , especially for the creation of dynamic web pages . It is important to understand the usefulness of ASP.NET applications in building efficient , robust and reliable .

Below are my top 7 tips to improving ASP.net application Performance :

1 . Use HTTPServerUtility.Transfer instead of Response.Redirect

Redirect 's are also very chatty . They should only be used when you are transferring people to another physical web server . For any transfers within your server , use . Transfer! You will save a lot of needless HTTP requests.

2 . Always check Page.IsValid when using Validator Controls

So you've dropped on some validator controls , and you think your good to go Because ASP.net does everything for you ! Right ? Wrong ! All that happens if bad the data is received is the IsValid flag is set to false . So the make sure you check Page.IsValid before processing your forms !

3 . Deploy with Release Build

Make sure you use the Release Build mode and not Debug Build when you deploy your site to production . If you think this does not matter , think again . By running in debug mode , you are creating PDB 's and cranking up the timeout . Deploy Release mode and you will see the speed improvements .

4 . Pre - Compiling ASP.NET Application

When compiling an ASP.NET application project , a single assembly is created to hold all the application 's code but the web pages ( . Aspx ) and user controls ( . Ascx ) not compiled and be deployed as it is . In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder .

To reduce the time of the first request a web application can be pre-compiled , Including all the code , pages , and user controls , by using the ASP.NET compilation tool ( Aspnet_compiler.exe ) . Running this tool in production servers can reduce the delay users experience on first requests .

a. Open a command prompt in your production server .
b. Navigate to the % windir % Microsoft.Net folder
c. Navigate to either the Framework or Framework64 According to the configuration of the web application 's application pool .
d. Navigate to the framework version 's folder .
e. Enter the following command to start the compilation

Aspnet_compiler.exe - v / FullPathOfYourWebApplication

5 . Disable Session State

Disable Session State if you're not going to use it . By default it 's on . You can actually turn this off for specific pages, instead of for every page :

< % @ Page language = " c # " Codebehind = " WebForm1.aspx.cs "

AutoEventWireup = "false " Inherits = " WebApplication1.WebForm1 "

">EnableSessionState = "false " % >


mode value to Off. ">You can also disable it across the application in the web.config by setting the value to Off mode .

6 . Repeater Control Good, DataList, DataGrid, and DataView controls Bad

Asp.net is a great platform , unfortunately a lot of the controls that were developed are heavy in html , and create not the greatest scaleable html from a performance standpoint . ASP.net repeater control is awesome ! Use it ! You might write more code , but you will thank me in the long run !

7 . Create Per -Request Cache

Use HTTPContect.Items to add single page load to create a per - request caching.

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Create Dynamic menu with SQL Server Database in ASP.NET

clock August 5, 2016 22:44 by author Dan

Hi friends,in this article I will explain about How to Create Dynamic menu is one of the most important parts if a website development. So today I will show you how you can create dynamic css menu with database(SQL Server using in ASP.NET using CSS.

First we will search for the menu which we want to implement dynamically. After this we will create table in which we will add the menu item detail. In this article I have used two table one for parent and other for child table. In this child table contains the reference of parent table.

DBScript:


 CREATE TABLE Parent_Menu (
  ID int IDENTITY,
  ParentMenu_Name varchar(50),
  ParentMenu_URL varchar(150)
)

CREATE TABLE Child_Menu (
  ID int IDENTITY,
  Parent_ID int,
  ChildMenu_Name varchar(50),
  ChildMenu_URL varchar(150)
)

INSERT INTO Parent_Menu (ParentMenu_Name, ParentMenu_URL)
  VALUES ('Home', '#')
INSERT INTO Parent_Menu (ParentMenu_Name, ParentMenu_URL)
  VALUES ('Technology', '#')
INSERT INTO Parent_Menu (ParentMenu_Name, ParentMenu_URL)
  VALUES ('Contact US', '#')

INSERT INTO Child_Menu (Parent_ID, ChildMenu_Name, ChildMenu_URL)
  VALUES (1, 'Home', '~/Home.aspx')
INSERT INTO Child_Menu (Parent_ID, ChildMenu_Name, ChildMenu_URL)
  VALUES (2, 'ASP.NET', '~/Asp_Net.aspx')
INSERT INTO Child_Menu (Parent_ID, ChildMenu_Name, ChildMenu_URL)
  VALUES (2, 'C#', '~/CSharp.aspx')
INSERT INTO Child_Menu (Parent_ID, ChildMenu_Name, ChildMenu_URL)
  VALUES (2, 'MVC', '~/MVC.aspx')


ASP.NET:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Creating Dynamic CSS Menu From Database SQL Server in ASP.Net Using C#.Net/VB.NET
    </title>
    <style type="text/css">
        .ParentMenu
        {
            font-size: small;
            font-family: Tahoma;
            font-weight: bold;
            padding-left: 6px;
            padding-right: 6px;
            text-align: center;
            background-color: #8B008B;
            color: White;
            border: 1px solid black;
        }
      
        .ParentMenu:hover
        {
            font-family: Tahoma;
            font-weight: bold;
            padding-left: 6px;
            padding-right: 6px;
            text-align: center;
            border: 1px solid black;
            font-size: small;
        }
      
        .ChildMenu
        {
            background-color: #8B008B;
            font-weight: bold;
            font-family: Tahoma;
            padding-top: 4px;
            padding-bottom: 4px;
            padding-right: 5px;
            padding-left: 5px;
            text-align: left;
            font-size: small;
            color: White;
            border: 1px solid black;
        }
        .ChildMenu:hover
        {
            font-weight: bold;
            font-family: Tahoma;
            padding-top: 4px;
            padding-bottom: 4px;
            padding-right: 6px;
            padding-left: 6px;
            text-align: left;
            font-size: small;
            border: 1px solid black;
            background-color: Black;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Menu DynamicSelectedStyle-Font-Italic="true" ID="dynamicMENU" runat="server"
            Orientation="Horizontal" DynamicVerticalOffset="4" OnMenuItemClick="dynamicMENU_MenuItemClick">
            <StaticMenuItemStyle Width="100" CssClass="ParentMenu" />
            <DynamicMenuItemStyle Width="250" CssClass="ChildMenu" />
        </asp:Menu>
    </div>
    </form>
</body>
</html>


C#.NET:


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.Configuration;
using System.Data.SqlClient;

public partial class DynamicCSSMenu : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetMenu();
        }
    }

    public void GetMenu()
    {
        DataSet dsParentMenu = getPARENTMENU();
        DataRowCollection drcParentMenu = dsParentMenu.Tables[0].Rows;
        DataSet dsChildMenuAll = getCHILDMENU();
        DataTable drcChildMenuAll = dsChildMenuAll.Tables[0];

        MenuItem mainMENUITEM;
        MenuItem childMENUITEM;
        foreach (DataRow drParentMenu in drcParentMenu)
        {
            mainMENUITEM = new MenuItem(drParentMenu["ParentMenu_Name"].ToString());
            dynamicMENU.Items.Add(mainMENUITEM);
            DataRow[] drcChildMenu = drcChildMenuAll.Select("Parent_ID=" + "'" + drParentMenu["ID"].ToString() + "'");
            foreach (DataRow drSUBMENUITEM in drcChildMenu)
            {
                childMENUITEM = new MenuItem(drSUBMENUITEM["ChildMenu_Name"].ToString());
                mainMENUITEM.ChildItems.Add(childMENUITEM);

                childMENUITEM.NavigateUrl = drSUBMENUITEM["ChildMenu_URL"].ToString();
            }
        }
        mainMENUITEM = new MenuItem("Logout");
        dynamicMENU.Items.Add(mainMENUITEM);
    }

    public DataSet getPARENTMENU()
    {
        SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());
        string str_query = string.Empty;
        str_query = "SELECT * FROM Parent_Menu";
        SqlDataAdapter daPARENT = new SqlDataAdapter(str_query, myConnection);
        DataSet dsTEMP = new DataSet();
        daPARENT.Fill(dsTEMP, "tablePARENT");
        return dsTEMP;
    }

    public DataSet getCHILDMENU()
    {
        SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());
        string str_querychild = string.Empty;
        str_querychild = "SELECT * FROM Child_Menu";
        SqlDataAdapter daCHILD = new SqlDataAdapter(str_querychild, myConnection);
        DataSet dsTEMP = new DataSet();
        daCHILD.Fill(dsTEMP, "tableCHILD");
        return dsTEMP;
    }
    protected void dynamicMENU_MenuItemClick(object sender, MenuEventArgs e)
    {
        Response.Redirect("~/index.aspx");
    }
}


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.Configuration
Imports System.Data.SqlClient

Partial Public Class DynamicCSSMenu
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            GetMenu()
        End If
    End Sub

    Public Sub GetMenu()
        Dim dsParentMenu As DataSet = getPARENTMENU()
        Dim drcParentMenu As DataRowCollection = dsParentMenu.Tables(0).Rows
        Dim dsChildMenuAll As DataSet = getCHILDMENU()
        Dim drcChildMenuAll As DataTable = dsChildMenuAll.Tables(0)

        Dim mainMENUITEM As MenuItem
        Dim childMENUITEM As MenuItem
        For Each drParentMenu As DataRow In drcParentMenu
            mainMENUITEM = New MenuItem(drParentMenu("ParentMenu_Name").ToString())
            dynamicMENU.Items.Add(mainMENUITEM)
            Dim drcChildMenu As DataRow() = drcChildMenuAll.[Select]("Parent_ID=" + "'" + drParentMenu("ID").ToString() + "'")
            For Each drSUBMENUITEM As DataRow In drcChildMenu
                childMENUITEM = New MenuItem(drSUBMENUITEM("ChildMenu_Name").ToString())
                mainMENUITEM.ChildItems.Add(childMENUITEM)

                childMENUITEM.NavigateUrl = drSUBMENUITEM("ChildMenu_URL").ToString()
            Next
        Next
        mainMENUITEM = New MenuItem("Logout")
        dynamicMENU.Items.Add(mainMENUITEM)
    End Sub

    Public Function getPARENTMENU() As DataSet
        Dim myConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("con").ToString())
        Dim str_query As String = String.Empty
        str_query = "SELECT * FROM Parent_Menu"
        Dim daPARENT As New SqlDataAdapter(str_query, myConnection)
        Dim dsTEMP As New DataSet()
        daPARENT.Fill(dsTEMP, "tablePARENT")
        Return dsTEMP
    End Function

    Public Function getCHILDMENU() As DataSet
        Dim myConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("con").ToString())
        Dim str_querychild As String = String.Empty
        str_querychild = "SELECT * FROM Child_Menu"
        Dim daCHILD As New SqlDataAdapter(str_querychild, myConnection)
        Dim dsTEMP As New DataSet()
        daCHILD.Fill(dsTEMP, "tableCHILD")
        Return dsTEMP
    End Function
    Protected Sub dynamicMENU_MenuItemClick(sender As Object, e As MenuEventArgs)
        Response.Redirect("~/index.aspx")
    End Sub
End Class

The output of the above code as shown in the below figure.

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: Easy Steps to Add Numeric String in ASP.NET

clock July 25, 2016 20:20 by author Dan

Must Know Issue: Basics of String Format in .Net

Numeric Format

double dValue = 55000.54987D;

//displaying number in different formats

Response.Write("Currency Format: " + dValue.ToString("C") + "
");

Response.Write("Scientific Format: " + dValue.ToString("E") + "
");

Response.Write("Percentage Format: " + dValue.ToString("P") + "
");

/* OUTPUT */

Currency Format: $55,000.55
Scientific Format: 5.500055E+004
Percentage Format: 5,500,054.99 %

Getting Culture Specific String


double dValue = 55000.54987D;

//You can Remove this line

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

//This line will automatically detect client culture

//and display data accordingly

//Here culture has forcefully changed to german to

//view difference in output

CultureInfo ci = Thread.CurrentThread.CurrentCulture;

//displaying number in different formats

Response.Write("Currency Format: " + dValue.ToString("C",ci) + "
");

Response.Write("Scientific Format: " + dValue.ToString("E",ci) + "
");

Response.Write("Percentage Format: " + dValue.ToString("P",ci) + "
");

/* OUTPUT */

Currency Format: 55.000,55 €
Scientific Format: 5,500055E+004
Percentage Format: 5.500.054,99%

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET SignalR Hosting - ASPHostPortal.com :: How to Send Notification using ASP.NET SignalR

clock September 4, 2014 12:00 by author Jervis

What is SignalR?

ASP.NET SignalR is a library for developing applications needing real-time communication. In such applications as soon as data is generated on the server or some interesting event happens on the server the client needs to be updated with the latest data. The traditional approach to achieve this functionality is to make Ajax calls to the server periodically. However, this approach has its own pitfalls. Another way is to use HTML5 Web Sockets or Server Sent Events (SSE) to perform real-time communication. However, both of these techniques work only on the browsers supporting HTML5. SignalR uses HTML5 Web Sockets if the target browser supports them, otherwise it falls back to other techniques. The best part is that - as a developer you need not know these internal implementation details. Additionally, SignalR makes connection management, grouping and authorization easy. You can work with the high level API exposed by SignalR in your web applications without worrying too much about the internals of the communication technique used.

You can use SignalR in variety of situations, some of them are listed below:

  • Chat applications where two or more end users chat with each other in real-time.
  • Broadcasting notifications or messages to all or selected clients.
  • Real-time gaming applications.
  • Social networking websites.
  • Discussion boards where admins or members can communicate to other admins or members.

Example

To illustrate how SignalR can be used in an ASP.NET application you will develop a web form application as shown below:

The web application consists of two simple web forms, viz. AdminForm.aspx and ClientForm.aspx. The former web form is supposed to be used by an administrator to send notifications to all the clients connected at a given point of time. The later web form displays the notifications sent from the administrator to the end user. The notifications are displayed in a balloon that disappears after 5 seconds.

Getting SignalR

In order to develop the above application you should first install the SignalR library. You can get SignalR in couple of ways. Firstly you can install it as a NuGet package. To do so, open Tools > Library Package Manager > Package Manager Console and then issue the following command:

install-package Microsoft.AspNet.SignalR

Not only easier, but the recommended way is to install Microsoft ASP.NET and Web Tools 2012.2. Doing so will add certain project item templates in the Add New Item dialog as shown below:

You can use these templates (more on that later) instead of manually creating the respective project items.

Developing the Admin Web Form

Now let's develop the admin web form first. Begin by creating a new blank ASP.NET web forms application. Then right click on the project in the Solution Explorer and select Add New Item. Then add a new SignalR Hub Class to the project. This creates a new class that inherits from Hub base class.

namespace SignalRDemo
{
    public class MyHub1 : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}

The Hub class resides in the Microsoft.AspNet.SignalR namespace. A hub class can have any number of developer defined methods. These methods can then be called from a client side script. SignalR hubs provide a higher level RPC framework for your application. Additionally, you will find certain script files under the Scripts folder.

In this example you need a method - SendNotifications() - inside the hub class as shown below:

public void SendNotifications(string message)
{
    Clients.All.receiveNotification(message);
}

As you can see, the SendNotifications() method accepts a string parameter. Inside, it uses the Clients.All property to access all of the clients currently connected with the server. The receiveNotification() is a client side callback function that you will write in your jQuery code later. This way a notification is broadcast to all the connected clients. How the clients make use of the message is governed by the receiveNotification() client side function.

Next, add a Global.asax file to your web application and write the following code in the Application_Start event handler.

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}

The MapHubs() method registers default routes for SignalR hubs.

Now, add a web form to the project and name it as AdminForm.aspx. Add the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Admin Form Sending Notifications</title> 

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script> 

    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            $("#button1").click(function () {
                proxy.server.sendNotifications($("#text1").val());
            });

            $.connection.hub.start();
        });
    </script> 

</head>
<body>
    <input id="text1" type="text" />
    <input id="button1" type="button" value="Send" />
</body>
</html>

The AdminForm.aspx refers SignalR script files in the head section. Notice the code marked in the bold letters. First a variable named proxy is declared to hold a reference to a proxy of the remote hub class (NotificationHub). Make sure that the client side code uses camel casing in naming conventions. For example, NotificationHub is referred as notificationHub in the client code.

Next, the click event handler of the button is wired to a function. The client event handler calls the sendNotifications() method on the proxy object and passes the notification message entered in the textbox (see earlier figure to know what the admin form looks like).

Finally, the start() method of the hub is called to start the connection.

Developing the Client Web Form

Now that you have completed AdminForm.aspx let's develop the client web form. Add another web form to the project and name it ClientForm.aspx. Key-in the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Client Form Receiving Notifications</title>
    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            proxy.client.receiveNotification = function (message) {
                $("#container").html(message);
                $("#container").slideDown(2000);
                setTimeout('$("#container").slideUp(2000);', 5000);
            };

            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div class="notificationBalloon" id="container">
    </div>
</body>
</html>

The client code also declares a variable to hold a reference to the proxy hub object. It then wires a callback function receiveNotification (recollect that you used this name in the server side NotificationHub class). The receiveNotification() function receives the notification message sent by the server and displays it to the user after animating it using slideDown() and slideUp() jQuery functions. The notification message is automatically discarded after 5 seconds using the setTimeout() JavaScript function.

Finally, a connection is started by calling the start() method on the hub.

That's it! Run the AdminForm.aspx and load ClientForm.aspx in two or three browser windows or tabs. Now enter some message in the textbox from AdminForm.aspx and click on the Send button. All the browser windows showing ClientForm.aspx should show the notification message.

Summary

SignalR is a library that allows ASP.NET applications to perform real-time communication. If the target browser supports HTML5 SignalR uses Web Sockets otherwise fallback techniques are used. Additionally, SignalR provides an easy way for connection management, connection grouping and security for the communication. This article demonstrated a basic use of SignalR to send notifications to all the connected clients in real-time.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in