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 Hosting with Toronto Data Center - HostForLIFE.eu :: How To Convert A Password Into Complicated

clock October 27, 2015 00:22 by author Rebecca

In this tutorial, we will show you how to convert a password into complicated in ASP.NET. We will ise SHA1 or MD5 algorithm to work around for converting your password into complicated.

Follow these steps to make your password seems complicated in ASP.NET:

Step 1

Open Visual Studio and create an empty website. Give it a suitable name for example: [hashpass_demo].

Step 2

 In Solution Explorer you will get your empty website, then add a Web Form by going like this:

  • Right Click
  • Add New Item, then Web Form. Name it hashpass_demo.aspx.

Step 3

Now mcreate some design for your application by going to hashpass_demo.aspx and try the code like this:

    <%@ 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: 258px; 
            } 
            .style2 
            { 
                width: 239px; 
            } 
        </style> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div> 
         
            <table style="width:100%;"> 
                <tr> 
                    <td class="style1"> 
                        Enter Your Username:</td> 
                    <td class="style2"> 
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
                    </td> 
                    <td> 
                        <asp:Label ID="Label2" runat="server"></asp:Label> 
                    </td> 
                </tr> 
                <tr> 
                    <td class="style1"> 
                        Enter Your Password:  
                    </td> 
                    <td class="style2"> 
                        <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox> 
                    </td> 
                    <td> 
                        <asp:Label ID="Label1" runat="server"></asp:Label> 
                    </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" /> 
                    </td> 
                    <td> 
                         </td> 
                </tr> 
            </table> 
         
        </div> 
        </form> 
    </body> 
    </html> 

Your design will look like following picture snippet:

Step 4

Now it’s time for server side coding so that our application starts working. Open your hashpass_demo.aspx.cs file and code it like below:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.Security; 
     
    public partial class _Default : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
     
        } 
        protected void Button1_Click(object sender, EventArgs e) 
        { 
            string securepass = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "MD5"); 
            Label2.Text = "Your Username is-" + TextBox1.Text; 
            Label1.Text = "Your HashPassword is-" + securepass; 
            Label2.ForeColor = System.Drawing.Color.ForestGreen; 
            Label1.ForeColor = System.Drawing.Color.ForestGreen; 
       
        } 
    } 

Here is the output:

Good luck!

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. 



ASP.NET 4.6 Hosting Germany - HostForLIFE.eu :: How to Use C# to Track an IP Address

clock October 5, 2015 18:25 by author Rebecca

In this tutorial, you will learn how to track an IP address in ASP.NET using C#.

In ASP.NET it is also very easy to find IP address no matter whether user is behind the proxy or not, you can easily track the user in ASP.NET. So let's have a look over the following code:

    //To get the ip address of the machine and not the proxy use the following code      
                string strIPAddress = Request.UserHostAddress.ToString(); 
                strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
     
                if (strIPAddress == null || strIPAddress == "") 
                { 
                    strIPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString(); 
                } 

That's it! Easy right?

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. 



ASP.NET 4.6 Hosting Portugal - HostForLIFE.eu :: How to Use Script to Disable Auto Fill TextBoxes in Some Browsers

clock September 26, 2015 12:59 by author Rebecca

Recent's browsers like Chrome, Firefox, Internet Explorer and Safari has functionality of auto complete values in TextBoxes. If you have enabled this features in browser, every time you start to enter value in TextBox you get a drop down of prefilled values in that TextBox. This feature of browser can be disabled by the programming for a specific web form like payment form and other confidential information form of a web application.

In chrome browser, you can enable auto-fill as shown below:

Step 1

Then you will have a below form for online payment of product by credit card or debit card then it is mandatory to stop auto complete functionality of browser so that browser doesn’t save the confidential information of a customer’s credit card or debit card.

 

Step 2


Then, you can turn off auto-fill for your complete form by setting autocomplete attribute value to off as shown below:

<form id="Form1" method="post" runat="server" autocomplete="off">

 .

 .

</form>

Step 3

You can also turn off auto-fill for a particular TextBox by setting autocomplete attribute value to off as shown below:

<asp:TextBox Runat="server" ID="txtConfidential" autocomplete="off"></asp:TextBox>

Step 4

And you can also do this from code behind also like as:

txtConfidential.Attributes.Add("autocomplete", "off");

After doing one of above code you will see that there is no auto-fill.


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.

 



ASP.NET 4.6 Hosting UK - HostForLIFE.eu :: How to Use ASP.NET to Populate AJAX Control

clock September 17, 2015 12:03 by author Rebecca

The DynamicPopulate Control in the ASP.NET AJAX can call a page method and fill the resulting value in the target control on the page without a page refresh. The method call returns a form of  HTML string that is inserted as a child of the target element. The AJAX controls  work automatically. While it's possible to call (_doPostBack()) from JavaScript to trigger for a partial update. When  we use the ASP.NET DropDownList control, ASP.NET will verify that the items in the list are the same items the list contained when the page was rendered. Since we are adding items on the client side, a postback results in an ASP.NET validation error. This postback validation is designed to prevent users from editing your web pages and trying to submit invalid data. You can disable this validation but, for our purposes, it's simpler just to use a <select> tag.

Step 1

Open Visual Studio, Go to File->New->WebSite and Select ASP.NET Empty WebSite:

Step 2

  • Go to Solution Explorer and right-click.
  • Select Add->New Item.
  • Select WebForm.
  • Default.aspx page open

Step 3

Go to Default.aspx page and click on the [Design] option and drag control from Toolbox. Then, drag Panel control, Label, Button, Drop List control, ScriptManager control.

Step 4

The page contain a button with the ID PopList. The onclick attribute of this attribute calls the PopulateList() JavaScript function.

JavaScript Function

<title>my ajax application</title>
<style type="text/css">
        body
        {
            font-family: @BatangChe
            font-size: small;
            color: #555555;
        }
    </style>
    <script type="text/javascript">
        function PopulateList() {
            PageMethods.GetListData(1, OnPopulateList);
        }
        function OnPopulateList(list) {
            var dropList = document.getElementById('DropList');
            for (i = 1; i < 10; i++) {
                var option = document.createElement('OPTION');
                option.text = list[i].text;
                option.value = list[i].value;
                dropList.options.add(option);
            }
        }
    </script>

Step 5

Go to Default.aspx[Source] option and define the condition EnablePageMethod is "True" with ScriptManager and write a code:

<form id="form1" runat="server" style="background-color: #330D1E">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
        </asp:ScriptManager>
        <p style="background-color: #2FC8D0">
        </p>
        <p style="background-color: #C0D1AF">
           How to populate control in ajax
        </p>
        <p style="background-color: #B8C9C9">
            <input id="PopList" type="button" value="Populate List"
                onclick="PopulateList();" style="background-color: #A5DCBD" />
        </p>
        <p style="background-color: #784847">
            <select id="DropList" name="DropListName"
                style="width: 200px; background-color: #B3CEC6;">
            </select>
        </p>
        <p style="background-color: #808080">
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        </p>
        <p style="background-color: #9A96E9">
            <asp:Label ID="lblSubmitValue" runat="server" BackColor="#FFFFCC"
                BorderWidth="15px"></asp:Label>
        </p>
    </div>
    </form>

Step 6

Now we create List Data Class. The data returns a list of objects for this class. The class consist two member Text, Value.

public class ListData
        {
            public string text { get; set; }
            public int value { get; set; }
        }

Step 7

Now we define the method for Client Side JavaScript and method return the data (List Data object):

public static IEnumerable<ListData> GetListData(int arg)
        {
            List<ListData> list = new List<ListData>();
            for (int i = 0; i < 100; i++)
                list.Add(new ListData()
                {
                    text = String.Format("List Item {0}", i),
                    value = i
                });
            return list;
        }

Step 8

The collection represents the raw values being posted to the page of List Data Items. Then these data items consist of the following namespace are use it.

using System.Collections.Generic;

Step 9

Now go to the Default.aspx.cs file; write code for the method to be called from client-side JavaScript:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["DropListName"] != null)
                lblSubmitValue.Text = String.Format("Submitted Value: \"{0}\"",
                    Request.Form["DropListName"]);
        }
        public class ListData
        {
            public string text { get; set; }
            public int value { get; set; }
        }
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static IEnumerable<ListData> GetListData(int arg)
        {
            List<ListData> list = new List<ListData>();
            for (int i = 0; i < 100; i++)
                list.Add(new ListData()
                {
                    text = String.Format("List Item {0}", i),
                    value = i
                });
            return list;
        }
    }

Step 10

Now run the application pressing F5.

This page demonstrate how to dynamically populate a control using AJAX.

Step 11

Click on the populate list button to populate the dropdown list.

Step 12

Now click on the Submit button to submit the selected value back to the server.

Step 13

Now, you will change the dropdown list item and click on the submit button to again submit the selected value back to the server.

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.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use ASP.NET and C# to Show First & Last Day in a Month

clock September 7, 2015 09:17 by author Rebecca

In this post, I'm going to show you how calculate the first day and last day of a month for one of the project. The method that I'm using is very simple.

Here is the code:

DateTime today = DateTime.Now; //current date

DateTime firstDay = today.AddDays(-(today.Day - 1)); //first day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

The Explanation

The Calculation of First Day

DateTime firstDay = today.AddDays(-(today.Day - 1));

Here I'm using the AddDays method which can add given number of days to the current date. Using today.Day I'm extracting the current date day as integer value, which is 21 in my example. The tricky part here is that I'm adding with the AddDays method total of 21-1 = 20 and using the minus sign, it's getting 20 days back (instead of 20 days forward).

The Calculation of the Last Day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

With today = today.AddMonths(1) I'm adding one month plus to the current date.
Before adding, for example the today value was {21-07-2015 17:27:50} - after adding +1 month, the today value is {21-08-2015 17:27:50}.
Then, with the last line, the trick is very similar to the firstDayDate calculation, we only go in minus to the number of days got from the today.Day integer value. We do not add today.Day-1 here because if you do, you will get the first day of the next month (so you know one more thing now, how to get the first day of the next month).
The lastDay value will be 31-07-2015 17:27:50

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.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use C# to Create AJAX Confirm Button Extension

clock August 31, 2015 09:03 by author Rebecca

In this tutorial, we will learn how to create and use an AJAX Confirm Button Extender using C#. This button can be used to warn people of what a button does once they press it. This control is used in lots of websites and it is easy to setup and use.

Step 1

Let's we create the form:

1. Start by Creating a new Web Form and naming it “Default.aspx”
2. Create a Button and a Label on the form named “Button1″ and “Label1″
3. Add an AJAX Script Manager to the Form so that you can use AJAX Controls:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <br />
                <br />
                <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                <asp:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server"
                    ConfirmText="Click OK to make the Label say OK or click Cancel to Cancel the Operation"
                    Enabled="True" TargetControlID="Button1">
                </asp:ConfirmButtonExtender>
            </ContentTemplate>
        </asp:UpdatePanel>
   
    </div>
    </form>
</body>
</html>


4. Add the Confirm Button Extender to the button by clicking the Smart tag and selecting Add Extender
5. Now the Web Form is complete, but it is not ready to be run yet. You must create the code behind.

Step 2

1. Double click on the Button Control in the Design View to open up the Code window.
2. Enter the Code Below, this code would normally make the Label say OK every time you click the button, however the code in the front end only lets it run once you confirm.
3. Once this code is in you can go ahead and run the project and see how it works:

protected void Button1_Click(object sender, EventArgs e)
        {
           
            Label1.Text = "you clicked OK";
        }

Happy coding!

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.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use jQuery to Show Row's Number in ASP.NET GridView

clock August 21, 2015 06:17 by author Rebecca

In this article, I will explain how to get the total count of the number of rows in ASP.NET GridView and also how to get the count of the number of all rows except the First (Header) row in ASP.Net GridView using jQuery.

HTML Markup

 The following HTML Markup consists of an ASP.NET GridView with three BoundField columns and a Button to get count (number) of rows in ASP.NET GridView using jQuery:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
    </Columns>
</asp:GridView>
<br />
<br />

<asp:Button ID="btnGetCount" Text="Count Rows" runat="server" />

NameSpaces

You will need to import the following namespace.

C#
using System.Data;
 
VB.Net
Imports System.Data

Binding the ASP.NET GridView Control

The GridView is populated with a dynamic DataTable with some dummy data inside the Page Load event.

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "1", "United States");
        dt.Rows.Add(2, "2", "India");
        dt.Rows.Add(3, "3", "France");
        dt.Rows.Add(4, "4r", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "1", "United States")
        dt.Rows.Add(2, "2", "India")
        dt.Rows.Add(3, "3", "France")
        dt.Rows.Add(4, "4", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

How to Get Row's Number in ASP.NET Gridview using jQuery

Inside the document ready event handler, the Button has been assigned a jQuery click event handler. When the Button is clicked, the total count of the number of rows and the count of the number of all rows except the First (Header) row in ASP.NET GridView is determined using jQuery.

The total count of the number of rows in ASP.NET GridView is determined by selecting all the HTML TR elements using jQuery. he count of the number of all rows except the First (Header) row in ASP.NET GridView is determined by selecting only those HTML TR elements which contain HTML TD (Cell) element and skipping all the HTML TR elements which contain HTML TH (Header Cell) element.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnGetCount]").click(function () {
            var totalRowCount = $("[id*=GridView1] tr").length;
            var rowCount = $("[id*=GridView1] td").closest("tr").length;
            var message = "Total Row Count: " + totalRowCount;
            message += "\nRow Count: " + rowCount;
            alert(message);
            return false;
        });
    });
</script>

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.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: Best Regular Expressions to Validate Email Address

clock August 14, 2015 07:12 by author Rebecca

Email address are the means of communication with people around the world. While processing forms email address validation plays an important. Proper email validation strengthen our contact list, ban spamming and protect us from robot form filling (Form AutoFill).

Here we are going to design a regular expression pattern to validate email address which will check to make sure an e-mail address is a valid address, and in proper format means containing an username, at sign (@), and valid hostname. For example, admin@samplehost.com is valid, but SPAM@badhost is invalid. Most of email service provides limit the use of literals for email address creation. Only letters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) are allowed and no special characters are accepted. You can add or remove any literals to your regular expression.

Regular Expression Pattern

^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$
email with IP -
^([a-zA-Z0-9_\-\.]+)@(([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d))$

A description of the regular expression:

1]: A numbered capture group. [[a-zA-Z0-9_\-\.]+]
Any character in this class: [a-zA-Z0-9_\-\.], one or more repetitions
@
Any character in this class: [a-z0-9-], one or more repetitions
[2]: A numbered capture group. [\.[a-z0-9-]+], any number of repetitions
\.[a-z0-9-]+
Literal .
Any character in this class: [a-z0-9-], one or more repetitions
[3]: A numbered capture group. [\.[a-z]{2,3}]
\.[a-z]{2,3}
Literal .
Any character in this class: [a-z], between 2 and 3 repetitions

Sucessful Matches:
space@between.co.in
te_s-t@tcs.co.in
rebecca@cassidy.server.address.com
email with IP
test@123.123.234.123
xyz@16.5.1.3

How It Works:
This regular expression will check for valid email address in which Only letters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) are allowed and no special characters are accepted. Here we are going to search three group and @ sign.

First first group will check valid conbination of characters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) followed by "@". Then we check for host name(tipsntracks,yahoo, google etc) and host type(.com, .biz, .co.in etc)

ASP.NET

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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>U.S. Social Security Numbers</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>Valid Format: 123-45-6789</span><br />
<asp:TextBox id="txtInput" runat="server"></asp:TextBox><br />
<asp:RegularExpressionValidator Id="vldRejex" RunAt="server" ControlToValidate="txtInput" ErrorMessage="Please enter a valid email address" ValidationExpression="^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$">
</asp:RegularExpressionValidator><br />
<asp:Button Id="btnSubmit" RunAt="server" CausesValidation="True" Text="Submit"></asp:Button>
</div>
</form>
</body>
</html>

C#.NET

//use System.Text.RegularExpressions befour using this function
public bool vldEmail(string emlAddress)
{
//create Regular Expression Match pattern object
Regex myRegex = new Regex("^([a-zA-Z0-9_\\-\\.]+)@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$");
//boolean variable to hold the status
bool isValid = false;
if (string.IsNullOrEmpty(emlAddress))
{
isValid = false;
}
else
{
isValid = myRegex.IsMatch(emlAddress);
}
//return the results
return isValid;
}

VB.NET

‘Imports System.Text.RegularExpressions befour using this function
Public Function vldEmail(ByVal emlAddress As String) As Boolean
‘create Regular Expression Match pattern object
Dim myRegex As New Regex("^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$")
‘boolean variable to hold the status
Dim isValid As Boolean = False
If emlAddress = "" Then
isValid = False
Else
isValid = myRegex.IsMatch(emlAddress)
End If
‘return the results
Return isValid
End Function

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.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use ASP.NET and C# to Send Email with Template

clock August 12, 2015 05:55 by author Rebecca

When bulding professional web applications, there can be so many emails to be sent to users and writing the templates for each of this email inside code is not a good move. Here we can use email templates. First create a folder some where in your application directory as "MailTemplates" or some other suitable name. Now create a text file or html file for template.

In this example, we are creating a sample template named welcome.htm:

Hi, <%=name%>

This is a sample mail template for demonstrating usage of email templates in asp.net

<a href="<%=url%>">Click here to read the article</a>
<a href="<%=rooturl%>">http://example.com/</a>

Now, we are creating an email utility for preparing and sending emails:

public static void SendMail(string fromAddress, string toAddress, string subject, string body)
       {
           using (MailMessage mail = BuildMessageWith(fromAddress, toAddress.Replace(',', ';'), subject, body))
           {
               SendMail(mail);
           }
       }
       public static void SendMail(MailMessage mail)
       {
           try
           {
               SmtpClient smtp = new SmtpClient("your smtp host",port);
               smtp.Send(mail);
           }
           catch (Exception e)
           {
            
           }
       }
       //build a mail message
       private static MailMessage BuildMessageWith(string fromAddress, string toAddress, string subject, string body)
       {
           MailMessage message = new MailMessage
           {
               Sender = new MailAddress(Settings.WebMasterEmail), // on Behave of When From differs
               From = new MailAddress(fromAddress),
               Subject = subject,
               Body = body,
               IsBodyHtml = true,
           };

           string[] tos = toAddress.Split(';');

           foreach (string to in tos)
           {

               message.To.Add(new MailAddress(to));
           }

           return message;
       }
    // read the text in template file and return it as a string
       private static string ReadFileFrom(string templateName)
       {
           string filePath = System.Web.HttpContext.Current.Server.MapPath("~/MailTemplates/"+templateName);

           string body = File.ReadAllText(filePath);

           return body;
       }
       // get the template body, cache it and return the text
       private static string GetMailBodyOfTemplate(string templateName)
       {
           string cacheKey = string.Concat("mailTemplate:", templateName);
           string body;
           body = (string)System.Web.HttpContext.Current.Cache[cacheKey];
           if (string.IsNullOrEmpty(body))
           {
               //read template file text
               body = ReadFileFrom(templateName);

               if (!string.IsNullOrEmpty(body))
               {
                   System.Web.HttpContext.Current.Cache.Insert(cacheKey,body, null,DateTime.Now.AddHours(1),System.Web.Caching.Cache.NoSlidingExpiration);
               }
           }

           return body;
       }
       // replace the tokens in template body with corresponding values
       private static string PrepareMailBodyWith(string templateName, params string[] pairs)
       {
           string body = GetMailBodyOfTemplate(templateName);

           for (var i = 0; i < pairs.Length; i += 2)
           {
               body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
           }
           return body;
       }
 public static string FormatWith(this string target, params object[] args)
        {
            return string.Format(Constants.CurrentCulture, target, args);
        }

Now let's send the email:

string subject = "Welcome";
string body = PrepareMailBodyWith("welcome.htm", "name", "Anoop", "url", "http://waytocoding.blogspot.com/","rooturl","http://waytocoding.blogspot.com/");
SendMail("from@domain.com", "to@domain.com", subject, body);

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.



ASP.NET 5 Hosting - HostForLIFE.eu :: Converting HTML to Plain Text in ASP.NET

clock August 6, 2015 05:48 by author Rebecca

Sometimes you want to remove tags from HTML and get only plain text. In general, this is simple task but there are few drawbacks in some scenarios. The simplest solution is to just remove all tags from given HTML without any formatting.

You can do it with code like this:

[ C# ]

public string RemoveHTMLTags(string HTMLCode)
{
 return System.Text.RegularExpressions.Regex.Replace(
   HTMLCode, "<[^>]*>", "");
}

[ VB.NET ]

Public Function RemoveHTMLTags(ByVal HTMLCode As String) As String
 Return System.Text.RegularExpressions.Regex.Replace( _
   HTMLCode, "<[^>]*>", "")
End Function

Better HTML to plain text conversion\

Example above removes any tag from HTML. This is good enough in some scenarios, but there are some issues too:

- Text inside HEAD tag will be visible too
- Empty spaces &nbsp; and new lines <br /> or paragraph <p> will be lost
- Unwanted empty spaces that are invisible in HTML will show in plain text, and that will distract text even more
- Special characters like &amp; or &copy etc. will not be translated etc

To solve all these problems, you need a little more processing of input HTML. Next function will provide better HTML to text conversion:

[ C# ]

// This function converts HTML code to plain text
// Any step is commented to explain it better
// You can change or remove unnecessary parts to suite your needs

public string HTMLToText(string HTMLCode)
{
 // Remove new lines since they are not visible in HTML
 HTMLCode = HTMLCode.Replace("\n", " ");

 
 // Remove tab spaces
 HTMLCode = HTMLCode.Replace("\t", " ");
 
 // Remove multiple white spaces from HTML
 HTMLCode = Regex.Replace(HTMLCode, "\\s+", " ");
 
 // Remove HEAD tag
 HTMLCode = Regex.Replace(HTMLCode, "<head.*?</head>", ""
                     , RegexOptions.IgnoreCase | RegexOptions.Singleline);

 
 // Remove any JavaScript
 HTMLCode = Regex.Replace(HTMLCode, "<script.*?</script>", ""
   , RegexOptions.IgnoreCase | RegexOptions.Singleline);

 
 // Replace special characters like &, <, >, " etc.
 StringBuilder sbHTML = new StringBuilder(HTMLCode);

// Note: There are many more special characters, these are just
// most common. You can add new characters in this arrays if needed
 string[] OldWords = {"&nbsp;", "&amp;", "&quot;", "&lt;",
   "&gt;", "&reg;", "&copy;", "&bull;", "&trade;"};
 string[] NewWords = {" ", "&", "\"", "<", ">", "®", "©", "•", "â„¢"};
 for(int i = 0; i < OldWords.Length; i++)
 {
   sbHTML.Replace(OldWords[i], NewWords[i]);
 }

 
 // Check if there are line breaks (<br>) or paragraph (<p>)
 sbHTML.Replace("<br>", "\n<br>");
 sbHTML.Replace("<br ", "\n<br ");
 sbHTML.Replace("<p ", "\n<p ");

 
 // Finally, remove all HTML tags and return plain text
 return System.Text.RegularExpressions.Regex.Replace(
   sbHTML.ToString(), "<[^>]*>", "");
}

[ VB.NET ]

' This function converts HTML code to plain text
' Any step is commented to explain it better
' You can change or remove unnecessary parts to suite your needs

Public Function HTMLToText(ByVal HTMLCode As String) As String
 ' Remove new lines since they are not visible in HTML
 HTMLCode = HTMLCode.Replace("\n", " ")
 
 ' Remove tab spaces
 HTMLCode = HTMLCode.Replace("\t", " ")
 
 ' Remove multiple white spaces from HTML
 HTMLCode = Regex.Replace(HTMLCode, "\\s+", "  ")
 
 ' Remove HEAD tag
 HTMLCode = Regex.Replace(HTMLCode, "<head.*?</head>", "" _
   , RegexOptions.IgnoreCase Or RegexOptions.Singleline)

 
 ' Remove any JavaScript
 HTMLCode = Regex.Replace(HTMLCode, "<script.*?</script>", "" _
   , RegexOptions.IgnoreCase Or RegexOptions.Singleline)
 

 ' Replace special characters like &, <, >, " etc.
 Dim sbHTML As StringBuilder = New StringBuilder(HTMLCode)

 ' Note: There are many more special characters, these are just
 ' most common. You can add new characters in this arrays if needed

 Dim OldWords() As String = {"&nbsp;", "&amp;", "&quot;", "&lt;", _
    "&gt;", "&reg;", "&copy;", "&bull;", "&trade;"}
 Dim NewWords() As String = {" ", "&", """", "<", ">", "®", "©", "•", "â„¢"}
 For i As Integer = 0 To i < OldWords.Length
   sbHTML.Replace(OldWords(i), NewWords(i))
 Next i

 
 ' Check if there are line breaks (<br>) or paragraph (<p>)
 sbHTML.Replace("<br>", "\n<br>")
 sbHTML.Replace("<br ", "\n<br ")
 sbHTML.Replace("<p ", "\n<p ")

 
 ' Finally, remove all HTML tags and return plain text
 Return System.Text.RegularExpressions.Regex.Replace( _
    sbHTML.ToString(), "<[^>]*>", "")
End Function

HTML to plain text ASP.NET example

Now, you can build an example that convert HTML to plain text. Create new web page with one Button control and two TextBox controls, like on image bellow:

First TextBox control ID will be tbHTML and second TextBox control ID set to tbPlainText. On button's click write this code:

[ C# ]

protected void btnTextToHTML_Click(object sender, EventArgs e)
{
 tbPlainText.Text = HTMLToText(tbHTML.Text);
}


[ VB.NET ]

Protected Sub btnTextToHTML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTextToHTML.Click
 tbPlainText.Text = HTMLToText(tbHTML.Text)
End Sub

Please note that HTML is considered as dangerous input. To make this example works you need to add ValidateRequest="false" part to @Page directive. Otherwise, you'll get an error "A potentially dangerous Request.Form value was detected from the client...)" like on next image.

 

When you set ValidateRequest parameter to false, you can run an example. Place some HTML code to tbHTML TextBox control and click on Button. Plain text will be extracted from given HTML and shown in tbPlainText.

As you see, there are few different options when converting HTML to plain text. Depending of your needs you can only remove tags or provide additional formatting. Suggested HTMLToText function is not perfect. You can make it better if you add all symbols or add line breaks for new table rows, or add tab spaces for evey new table cell etc. Be aware that with every new option included this function becomes slower. If you overdo the conversion could be unsatisfactory, especially if you have large HTML files. Happy coding!

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.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