Showing posts with label Asp.Net. Show all posts
Showing posts with label Asp.Net. Show all posts

Tuesday 17 October 2017

How to trigger button click event when Enter key pressed in Textbox?

In this post, I will explain How to trigger button click event when Enter key pressed in Textbox?.

To trigger the Button click event when user press Enter Key in Textbox, I have used JavaScript function call with Textbox "onkeypress" event. There is no server-side keypress event for an ASP.Net Textbox. When the user presses any key, JavaScript function check whether it is an Enter key with the help of char code. If pressed key is Enter key then JavaScript function triggers an Asp.Net Button click event. Please go through below code for details.

HTML Code

<%@ Page Language = "C#" AutoEventWireup = "true" CodeBehind = "TriggerButtonClickEvent.aspx.cs" Inherits = "TestApplication.TriggerButtonClickEvent"  %>

<!DOCTYPE html>

<html>
<head>
    <title> How to trigger button click event when Enter key pressed in textbox? </title>

    <script type="text/javascript" language="javascript">

        function TriggerButtonClick(obj, event) {
            var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            if (keyCode == 13) {
                document.getElementById(obj).click();
                return false;
            }
            else {
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">

        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

        <asp:Button ID="btnSubmit" runat="server" OnClick = "Button1_Click" />
    </form>
</body>
</html>

C#.Net Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestApplication
{
    public partial class TriggerButtonClickEvent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtName.Attributes.Add("onkeypress", "return TriggerButtonClick('" + btnSubmit.ClientID + "', event)");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Response.Write("Button click event triggered!");
        }
    }
}




Sunday 8 October 2017

MVC (Model, View and Controller)

In this post, I will explain MVC (Model, View and Controller).

MVC stands for Model, View and Controller. MVC separates an application into three components - Model, View and Controller.

Model: Model represents the shape of the data and business logic. It maintains the data of the application. Model objects retrieve and store model state in a database. Model is a data and business logic.

View: View is a user interface. View display data using the model to the user and also enables them to modify the data. View is a User Interface.

Controller: Controller handles the user request. Typically, the user interacts with View, which in-tern raises appropriate URL request, this request will be handled by a controller. The controller renders the appropriate view with the model data as a response. The controller is a request handler.

The following figure illustrates the interaction between Model, View and Controller.

Interaction between Model, View and Controller
Interaction between Model, View and Controller

Thursday 14 September 2017

Asp.Net Ajax Control Toolkit ColorPicker control extender

In this post, I will explain how you can use the Asp.Net Ajax Control Toolkit ColorPicker control extender.

The ColorPicker control extender displays a popup dialogue that enables you to select a colour. The ColorPicker is useful whenever you want to provide an easy to use user interface for a user to pick a colour.

Suppose you want to create a website that enables the user to create a customized website header. User should be able to change Header Text and Header Background Color. 
For example, we have a web form with a header and body (See image 1). The header contains header text highlighted with background colour and body contains Header Text Textbox, Pick Color Textbox and Submit Button. 
ColorPicker
Image 1
Pick Color TextBox Control is extended with the ColorPicker Control Extender. To extend Pick Color TextBox with ColorPicker Control Extender you need to set TargetControlID, SampleControlID to txtPickColor. When user clicks on Pick Color Textbox a popup with colour picker control comes out and the user can select colour and when user select colour it shows sample colour and colour code in Pick Color Textbox (See image 2). 
Color Picker
Image 2
If User wants to change header text he can enter new header text in Header Text Textbox. When a user clicks Submit button, the header will change according to selected values (See image 3). 
Color Picker Extender
Image 3
Please see below code for more details.

HTML Code
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ColorPickerExtender.aspx.cs" Inherits="TestApplication.AjaxControlToolkit.ColorPickerExtender" %>
 <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
 <!DOCTYPE html>
 <html lang="">
<head runat="server">
    <title>Asp.Net Ajax Control Toolkit ColorPicker control extender</title>
</head>
<body>
    <form id="form1" runat="server" style="margin: 100px;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:Panel runat="server" GroupingText="Color Picker Extender" Width="400px" Font-Bold="true" Font-Size="Larger">
            <div id="header" runat="server" style="height: 60px; text-align: center;">
                <h2 id="headertext" runat="server" style=" margin: 0; padding: 10px;">Programming Trends</h2>
            </div>
            <div style="clear: both"></div>
            <div id="body" runat="server">
                <table style="margin: auto;">
                    <tr>
                        <td style="text-align: right;">
                            <h4 style="margin: 0; padding: 0;">Header Text : </h4>
                        </td>
                        <td>
                          <asp:TextBox ID="txtHeaderText" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            <h4 style="margin: 0; padding: 0;">Pick Color : </h4>
                        </td>
                        <td>
                            <asp:TextBox ID="txtPickColor" runat="server"></asp:TextBox>
                            <ajaxToolkit:ColorPickerExtender runat="server" TargetControlID="txtPickColor" ID="colorPicker" SampleControlID="txtPickColor" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
                        </td>
                    </tr>
                </table>
            </div>
        </asp:Panel>
    </form>
</body>
</html>

 C# Code
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestApplication.AjaxControlToolkit
{
    public partial class ColorPickerExtender : System.Web.UI.Page
    {
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtHeaderText.Text.Length != 0)
            {
                headertext.InnerText = txtHeaderText.Text.Trim();
            }
            if (txtPickColor.Text.Length != 0)
            {
                headertext.Attributes.Add("style", "margin: 0; padding: 10px;background-color: #" + txtPickColor.Text.Trim() + ";");
            }
        }
    }
}


Monday 28 August 2017

Application and Session Variable of Asp.Net

In this post, I will explain about the Application and Session Variable of Asp.Net

Application and Session variables can be used to store values that are global either to a particular user or to all users. Application variables and session variables stored in memory on the server works faster than storing and retrieving information in a database.

Application Variables

The Application variables are variables maintained on server-side by asp.net runtime. Application variables are the variables which remain common for the whole application for all the users. Application variable can be used across the whole application by any user. And they will end when the application stops or probably when they are killed forcibly. The ideal example of these kinds of variables is site counter. We can find out how many people accessed a particular site since the time it went live via application variables and incrementing the same on ever session start. We can use application start and application end events of global.asax file to start and end application variable.

Session Variables

The session variables are variables maintained on server-side by asp.net runtime. Each user is identified by a unique number called SessioID. Session variables are variables which remain common for the whole application but for one particular user. They also can be used across the whole application but each user will have a different copy. But they will end when a particular user session ends or probably when they are killed forcibly. The ideal example of this kind of variables is user id, User name. We can show massage like "Welcome Programming Trends" on every page of your site till Programming Trends logs off. We can use session start and session end events of global.asax file to start and end session variable.

Sunday 27 August 2017

QueryString in Asp.Net

In this post, I will explain about QueryString in Asp.Net.

A QueryString is a collection of characters appended to the end of a page URL. QueryString generally used to pass value from one web page to another web page using URL. A QueryString is easy to use and pass value within web pages. A Query strong can be used to pass a small amount of data, large data cannot be passed using QueryString. QueryString can be attached to URL by using the character "?". We can append single or multiple QueryString parameters to URL. Multiple QueryString parameters can be separated using "&" character.

Advantages:
1.    Easy to use.
2.    Server resources are not required.
3.    All browser supports QueryString.

Disadvantages:
1.    Large data cannot be passed using QueryString.
2.    QueryString are not secure because the parameter value is directly visible to the user.

Example
1. QueryString with a single parameter
www.programmingtrends.com?Param1=Google

1. QueryString with multiple parameters
www.programmingtrends.com?Param1=Google&Param2=India

How to Pass Ampersand (&) as QueryString parameter value in Asp.Net?

In this post, I will explain How to Pass Ampersand (&) as QueryString parameter value in Asp.Net?

In many cases, we need to pass value of variable from one page to another page using QueryString. It generally works fine but when a parameter value contains Ampersand (&) symbol then another page reads wrong parameter value. For example, if suppose Parameter value is "Larsen & Turbo" then another page will read it as "Larsen ".

This happens because generally, Ampersand (&) is used as a separator between 2 parameters in QueryString. You can see the following example,

www.programmingtrends.com?Param1=Google&Param2=India

To solve this problem with An ampersand (&) we can use Server.UrlEncode() function to encode Ampersand (&) in parameter value or we can encode parameter value by replacing '&' with '%26'.

Example:
string Param="Larsen & Turbo";

Response.Redirect("www.programmingtrends.com?param1=" + Server.UrlEncode( Param ));

OR

Response.Redirect("www.programmingtrends.com?param1=" + Param.Replace("&", "%26"));

Tuesday 15 August 2017

What is Web Services?

In this post, I will explain What is Web Services?

A web service is the communication platform between two different or same platform applications that allows using their web method. A web service can be created in any language, such as Java or other languages and that web service can be used in a .Net based application and a .Net web service can be used in other language application. Web services allow sharing data between multiple applications. Web services can be published, found, and used on the Web. Web services are described using XML based language WSDL (Web Services Description Language). Web Services are accessed using XML based protocol SOAP (Simple Object Access Protocol).

For example, if you have a domain and services layer you may create a server that your website, android/iPhone app, and console application may access without duplicating your business logic. Basically, it will be for retrieving data and then let your application decide what to do with that data.

You can use web services instead of C# classes in the following cases,
  • You want to expose some functionality to outside world/consumers/other applications
  • You want to decouple parts of your system so that they can be changed without affecting other parts of an application
  • You want to do make your application scalable, so you create web services and deploy those on different servers


Sunday 13 August 2017

How to send email in ASP.Net using C#

In this post, I will explain How to send email in ASP.Net C#?.

I am going to explain this with below example. In an example, we have one Asp.Net form with few controls as Name, Email, Phone No & Message and Submit Button. On Submit button click application will send one mail to the recipient email. In an example, I am using Gmail SMTP Server and Gmail email address with credentials to send an email. 

Required additional Namespaces - 
using System.Net;
using System.Net.Mail;

Required changes in Gmail account settings to allow sending an email using Asp.Net C# application.
1. Login Gmail account 
2. Go to My Account
3. Go to Sign In & Security
4. Go to Connected apps & sites
5. Change "Allow less secure apps:" settings to "ON"

Below is detailed HTML & C# code to send email using Asp.net C#.

HTML Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendMail.aspx.cs" Inherits="TestApplication.SendMail" %>

<!DOCTYPE html>
<html lang="">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <table cellspacing="0">
                            <tr>
                                <td style="text-align: left; height: 25px;">
                                    <asp:Label ID="lblMessage" runat="server" ForeColor="Red" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left">
                                    <asp:Label ID="label10" runat="server" Text="Name :"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left;">
                                    <asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left">
                                    <asp:Label ID="label12" runat="server" Text="Email :"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left;">
                                    <asp:TextBox ID="txtEmail" runat="server" ></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left">
                                    <asp:Label ID="label1" runat="server" Text="Phone No :"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left;">
                                    <asp:TextBox ID="txtPhoneNo" runat="server" MaxLength="14"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left">
                                    <asp:Label ID="label18" runat="server" Text="Message :"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left;">
                                    <asp:TextBox ID="txtMessage" runat="server" Height="80px" TextMode="multiline"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: center; padding-top: 10px;">
                                    <asp:Button ID="btnSubmit" runat="server"  OnClick="btnSubmit_Click" Text="SUBMIT" ValidationGroup="Submit" />
                                </td>
                            </tr>
                        </table>
    </div>
    </form>
</body>
</html>


C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;

namespace TestApplication
{
    public partial class SendMail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // settings to do with Gmail account
        

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            try
            {
                string Name, Email, PhoneNo,  Message, Body, Subject;

                Name = txtName.Text;
                Email = txtEmail.Text;
                PhoneNo = txtPhoneNo.Text;
                Message = txtMessage.Text;

                Subject = "Message "+ " From " + Name;

                Body = "Name :" + Name + "<br/>" + "<br/>"
                    + "Email :" + Email + "<br/>" + "<br/>"
                    + "PhoneNo :" + PhoneNo + "<br/>" + "<br/>"
                    + "Message :" + Message + "<br/>" + "<br/>"
                     + "Date :" + DateTime.Now.ToString();

                MailMessage Msg = new MailMessage();
                Msg.From = new MailAddress(Email);
                
                //Recipient e-mail address. You can add multiple email address to a recipient list

                Msg.To.Add("abc@gmail.com,info@abc.co.in");

                Msg.Subject = Subject; 
                Msg.Body = Body; 
                Msg.IsBodyHtml = true;

                // SMTP server name or IP and port details.
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                //smtp.Host = ""127.0.0.1"";

                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "abc@abc");
                smtp.EnableSsl = true;
                smtp.Send(Msg);

                // Clearvaluess
                txtName.Text = "";
                txtEmail.Text = "";
                txtPhoneNo.Text = "";
                txtMessage.Text = "";

                lblMessage.Text = "Thanks for Contacting us !!!";
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message.ToString();
            }
        }
    }
}
send email in ASP.Net