ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: Dynamically from code behind in asp.net using C#

clock January 24, 2017 11:50 by author Armend

In this example we explain that how to change CSS dynamically from code behind in asp.net using C#. or how to change CSS file programmatically in C# code(back end  code) in asp.net. Some time we have requirement like if user click on or check Lightweight button then Lightweight CSS is apply to the application for these user only same like if user checked or click on Professional button then Professional look is applied to the application for these user only these totally is dynamic and depend on user requirement.


So how to change or switch CSS file dynamically from code behind in asp.net using C#.

ChangeCSSFileDynamically.aspx:


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

<!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 id="Head1" runat="server">
    <title>Dynamically change (switch) CSS file programmatically from code behind in ASP.Net</title>
    <link id="lnkCSS" runat="server" href="~/CSS/Lightweight.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="This is a Label" CssClass="label"></asp:Label>
    <hr />
    <asp:RadioButton ID="chkLightWeight" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="LightWeight"
        OnCheckedChanged="chkLightWeight_CheckedChanged1" />
    <asp:RadioButton ID="chkProfessional" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="Professional"
        OnCheckedChanged="chkProfessional_CheckedChanged1" />
    </form>
</body>
</html>

ChangeCSSFileDynamically.aspx.cs:

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

namespace WebApplication1
{
    public partial class ChangeCSSFileDynamically : System.Web.UI.Page
    {

        protected void chkLightWeight_CheckedChanged1(object sender, EventArgs e)
        {
            lnkCSS.Attributes["href"] = "~/CSS/Lightweight.css";
        }

        protected void chkProfessional_CheckedChanged1(object sender, EventArgs e)
        {
            lnkCSS.Attributes["href"] = "~/CSS/Professional.css";
        }
    }
}

Lightweight.css:

body
{
    font-family:Times New Roman;
    font-size:10pt;
}
.label
{
    font-weight:bold;
    color:Purple;
}

Professional.css:

body
{
    font-family:Arial;
    font-size:bold;
}
.label
{
    font-weight:bold;
    color:yellow;
}

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 :: ASP.NET Seo Tips

clock June 21, 2016 20:41 by author Armend

When running an online business, majority of our focus is on the design, architecture of the website and how efficiently it displays our product. These are not the only things that are required to target the infinite Internet audience. One need to keep in mind that the main source of audience come from search engines such as Google, Yahoo, Bing and others. So the application or the website should be able to follow simple rules and handle your business efficiently. ASP.NET application is spreading rapidly and if you are using an ASP.NET website few simple guidelines has to be considered. The below mentioned points need to be implemented:

 

Page Titles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  •     External stylesheets and not inline CSS
  •     -js files instead of inline JavaScript
  •     HTML comments is not encouraged
  •     Avoid massive line breaking
  •     Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed.

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.

 



ASP.NET 5 Hosting - ASPHostPortal :: SEO For ASP.NET Web Sites

clock December 16, 2015 00:36 by author Kenny

SEO For ASP.NET Web Sites

One of the main sources of audience for these internet applications are the Search Engines like Google, Bing, Yahoo etc. Hence, the end application should not only handle your business problems efficiently but also follow some simple rules so that it yields good results in internet arena. This article, will list some of the simple guidelines which you need to consider if your Asp.Net application is an internet site.

1.    Add descriptive and unique Page Title for every page

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file. Refer below,

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" Title="My Home Page"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

In code behind,

Page.Title = "My Home Page";

2.    Links should be hyperlinks, no linkbutton or javascript navigation for crawlable links

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). Javascript navigations are not search engine friendly since search engines will not understand it.

3.    Use javascript navigation for site related pages that have no search values

Page rank is distributed across the links on your page. Some of the internal website pages like About us, disclaimer, Registration, login, contact us, user profile pages can be navigated through javascript so that the page rank are not distributed to them. Doing like this will make rest of the crawlable content links benefited.

4.    Add Meta Keyword and Description tag for every page

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers. You can dynamically set the meta tags from codebehind file using the below code,

HtmlHead head = (HtmlHead)Page.Header;

 HtmlMeta metasearch1 = new HtmlMeta();

 HtmlMeta metasearch2 = new HtmlMeta();  

 metasearch1.Name = "descriptions";

 metasearch1.Content = "my personal site";

 head.Controls.Add(metasearch1);

 metasearch2.Name = "keywords";

 metasearch2.Content = "ASP.Net,C#,SQL";

 head.Controls.Add(metasearch2);

The above code will add the below Meta tags to output html.

<meta name="descriptions" content="my personal site" />

<meta name="keywords" content="ASP.Net,C#,SQL" />

In ASP.Net 4.0, Microsoft added 2 new properties on the Page directive (Page object) that lets you to define the Meta keywords and Description declaratively and dynamically from codebehind.

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net,C#" MetaDescription="This is an asp.net site that hosts asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>

In codebehind,

protected void Page_Load(object sender, EventArgs e)

    {

        Page.MetaKeywords = "asp.net,C#";

        Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";

    }

The similar can thing can be achieved in previous versions of .Net Framework by using a custom BasePage class.

5.    Make descriptive urls

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://www.example.com/products.aspx?catid=C91E9918-BEC3-4DAA-A54B-0EC7E874245E is not descriptive as http://www.example.com/Windows-Hosting

Apart from other parameters, search engines will also consider the website url to match your page for a searched keyword.



ASP.NET Hosting - ASPHostPortal.com :: Sending an email using exchange server from the ASP.NET Application

clock February 2, 2015 07:27 by author Dan

The .NET Framework 1.x had a System.web.mail class to send an email from the ASP.NET system. While this namespace and these classes still exist in the .NET Framework form 2.0 and later, they have been expostulated and supplanted by the new Mail API in the System.net.mail namespace in the Asp.net 2.0 structure. Asp.net 1.x's System.web.mail API was focused around CDO libraries. With the new Apis, Microsoft moved far from CDONTS based wrapper Apis and composed the new API utilizing Com+ segments to enhance the execution.

ASP.NET 2.0 sends an email utilizing Smtpclient class. In the most fundamental arrangement, You need to set the hostname of the hand-off server in the event that you are utilizing trade server or localhost in the event that you are utilizing neighborhood SMTP administration, port (25 as a matter of course), authentican certifications, or pointed out pickup index through the Deliverymethod property.

Here is the template for the System.NET.Mail configuration.

<configuration>
<!– Add the email settings to the element –>
<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectory” from=”fromemailaddress”>
<network
host=”relayServerHost”
port=”portNumber”
userName=”username”
password=”password”
defaultCredentials=”true/false”/>
</smtp>
</mailSettings>
</system.net>
</configuration>

localhost – local web server SMTP administration – If you need to send an email through neighborhood SMTP Service of the web server, basically include emulating lines of code in your web.config to send an email from the ASP.NET Pages.

<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectoryFromIis”>
<network host=”(localhost)” port=”25″ defaultCredentials=”true” />
</smtp>
</mailSettings>
</system.net>

Exchange Server – If you need to send an email from existing trade server email account, you need to setup the transfer administration from your webserver to trade server. Emulating web.config setup permits you utilize hand-off administration for trade server.

How about we say's exchange server name is "exmail.domainname.com", exchange username and secret key is "exchangeuserid" and "exchangepassword", you web.config settings would be

<system.net>
<mailSettings>
<smtp>
<network host=”exmail.domainname.com” port=”25″ userName=”exchangeuserid” password=”exchangepassword” defaultCredentials=”false” />
</smtp>
</mailSettings>
</system.net>

Next step would be to make a class to send a messages utilizing SMTP Service: Note that emulating code utilizes Web.config settings. Remarked out code won't utilize web.config mail settings. In spite of the fact that its preferrable, on the off chance that you don't need email designs in web.config document, utilize the remarked out code to design and send an email from the ASP.NET pages.

using System;using System.Net;using System.Net.Mail;
public class SMTPEmailSender
{
public SMTPEmailSender()
{
//
// TODO: Add constructor logic here
//
}

public static void SendSMTPEmail(string senderMailAddress,
string recipientMailAddress,
string mailSubject,
string mailBody)
{

//Create MailMessage to send an email.
MailMessage message = new MailMessage(senderMailAddress, recipientMailAddress);
message.Subject = mailSubject;
message.Body = mailBody;

//Use SMTPClient to send an email.
//Uses SMTP settings from web.config
SmtpClient client = new SmtpClient();
client.Send(message);

//Uses SMTP Settings from Code
/*
//Sample Code
//SmtpClient smtp = new SmtpClient(“exmail.domainname.com”, portnumber);
//smtp.Credentials = new NetworkCredential(“exchangeuserid”, “exchangepassword”, “DOMAIN”);
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //smtp.Send(message);
*/
}
}

Create a Test Page to send out emails. Here is the source code from the code behind to send an email from the test email page.

public partial class TestEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fromEmailAddress = “[email protected]“;
string recipientEmailAddress = “[email protected]“;
string mailSubject = “Nik’s Website: Test Email”;
string mailBody = “Test Email.”;
if (recipientEmailAddress != null && recipientEmailAddress.Trim().Length != 0)
{
SMTPEmailManager.SendSMTPEmail(fromEmailAddress, recipientEmailAddress, mailSubject, mailBody);
}
Response.Write(“Test Email Sent Out”);
}
}

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 :: How to Disable Cut, Copy and Paste in the Entire ASP.NET Web Form

clock January 22, 2015 06:22 by author Mark

This article shows how to restrict the use of cut, copy and paste by the end user in the whole page.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .

Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;


On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;


On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:

Conclusion

In this article, I have described how to restrict the user to use the cut, copy and paste facilities in the entire page and I hope it will be beneficial for you.

TOP No#1 Recommended ASP.NET MVC 5 Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal :: How to Delete Record in GridView Using ASP.Net Ajax and jQuery

clock January 13, 2015 06:14 by author Mark

How to Delete Record in GridView Using ASP.Net Ajax and jQuery

This article will explains how to delete record in GridView using ASP.NET Ajax and jQuery

  • Now first create the Employee table in the database.

CREATE TABLE tbl_Emp(Empid int NULL,EmpName varchar(250) NULL, Gender varchar(20), EmpAddress varchar(500) NULL,City varchar(250) NULL,Salary int NULL, Fk_DepId int)

  • And insert some records into the table:

INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(1, 'A' , 'Male', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(2, 'B' , 'Male', 'Demo Address', 'Ghaziabad', 0, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(3, 'C' , 'Male', 'Demo Address', 'Agra', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(4, 'D' , 'Female', 'Demo Address', 'Mathura', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(5, 'E' , 'Female', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(6, 'F' , 'Male', 'Demo Address', 'Agra', 5000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(7, 'G' , 'Male', 'Demo Address', 'Noida', 4000, 1)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(8, 'H' , 'Male', 'Demo Address', 'Agra', 4000, 5)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(9, 'I' , 'Male', 'Demo Address', 'Noida', 5000, 1) 

  • After creating the table create the application. New -> Web Site.
  • Provide the name “DeleteRecordfromGridViewUsingJQueryAjax”.
  • Then create a new item.

Your aspx page looks likes this:

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
        <title></title> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
            <div> 
                <asp:GridView ID="gvEmp" AutoGenerateColumns="false"CellPadding="4" runat="server"> 
                    <Columns> 
                    <asp:BoundField HeaderText="EmpId" DataField="EmpId"/>
                    <asp:BoundField HeaderText="EmpName"DataField="EmpName" />

                    <asp:BoundField HeaderText="Gender" DataField="Gender" /> 
            <asp:BoundField HeaderText="EmpAddress" DataField="EmpAddress" /> 
            <asp:TemplateField> 
            <ItemTemplate> 
            <asp:HiddenField ID="hdnEmpId" runat="server" Value='<%#Eval("EmpId") %>'></asp:HiddenField>                                  <asp:LinkButton ID="btnDelete" Text="Delete Emp" runat="server"OnClientClick="DeleteConfirmbox(this.id);"></asp:LinkButton>
                         </ItemTemplate> 
                        </asp:TemplateField> 
                    </Columns> 
          <HeaderStyle BackColor="#5d5d5d" FontBold="true"ForeColor="White" />
                </asp:GridView> 
            </div> 
        </form>
         <script src="Scripts/jquery-1.7.1.min.js"></script>        
        <script type="text/javascript"> 
            function DeleteConfirmbox(val) { 
                // confirm meg check for delete 
                var result = confirm('Are you sure delete Emp Record?'); 
                if (result) {        
                  // this is for get hdnvalue id 
                  var value = val.replace("btnDelete", "hdnEmpId"); 
                  $.ajax({ 
                  type: "POST", 
                  contentType: "application/json; charset=utf-8", 
                  url: "Default.aspx/DeletegvEmpData",//this for calling the web method function in cscode. 
                  data: '{empid: "' + $("#" + value).val() + '" }',// empid value                     
                  dataType: "json", 
                  success: OnSuccess, 
                  failure: function (data) { 
                  alert(data); 
                        }          
                    });                        
                    return false; 
                } 
            }        
            // function OnSuccess 
            function OnSuccess(response) { 
                return false; 
            if (response.d == 'true') 
            {              
            }      
        } 
    </script> 
</body> 
</html> 

  • Now add “using System.Data.SqlClient;” and “using System.Data;” in the code behind and write the following code to delete the record in the grid view in the database.

protected void Page_Load(object sender, EventArgs e)  
  {  
      if (!IsPostBack)  
      {  
          Bindgv();  
      }  
  }       
  protected void Bindgv()  
  {  
      SqlConnection con = new SqlConnection("data source=LENOVO;initial catalog=practise;UID=sa;PWD=connect;");       
      con.Open();  
      SqlCommand cmd = new SqlCommand("Select Top 10 EmpId, EmpName, Gender, EmpAddress from tbl_Emp", con);  
      SqlDataAdapter da = new SqlDataAdapter(cmd);  
      DataSet ds = new DataSet();  
      da.Fill(ds);  
      con.Close();  
      gvEmp.DataSource = ds;  
      gvEmp.DataBind();       
  }       
  [System.Web.Services.WebMethod]  
  public static string DeletegvEmpData(int empid)  
  {  
      string strmsg = string.Empty;  
      SqlConnection con = new SqlConnection("data source=LENOVO;initial catalog=practise;UID=sa;PWD=connect;");       
      SqlCommand cmd = new SqlCommand("delete from tbl_Emp where EmpId= @Empid", con);       
      con.Open();  
      cmd.Parameters.AddWithValue("@Empid", empid);  
      int retval = cmd.ExecuteNonQuery();  
      con.Close();       
      if (retval == 1)  
          strmsg = "true";  
      else  
          strmsg = "false";                   
      return strmsg;  
  }
Add the jQuery library reference in aspx page:
    <script src="Scripts/jquery-1.7.1.min.js"></script> 

Finished, Now you can run this page.

TOP Recommended ASP.NET Hosting

ASPHostPortal.com is the leading provider of Windows hosting and affordable ASP.NET, ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. Only $1.00 Month You can develop your bussines. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability. 

 

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Enabling Unobtrusive Validation From Scratch in ASP.NET 4.5 Webforms

clock December 19, 2014 04:55 by author Ben

I used to be fiddling with ASP.NET 4.5 and Visual Studio 2012 particularly with all the new Validation attributes and i identified they function great, specially the new unobtrusive validation, then I attempted to permit this sort of validation over a new Vacant Net Software, and that i identified that this just isn't out-of-the-box, you'll need to create some configurations to your Net Application.

You'll find a few ways to allow the unobtrusive validation over a Internet Software:

Through the web.config file

<configuration> 
  <appsettings> 
   <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"> 
  </add></appsettings> 
 </configuration> 

Via the Global.asax file

protected void Application_Start(object sender, EventArgs e)
{
   ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
}

On each page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.WebForms;
}

To disable the unobtrusive validation set the UnobtrusiveValidationMode property to None. Unobtrusive validation is actually enabled by default in ASP.Net 4.5.

We'll start with a simple example, create an Empty Web Application and add a MasterPage called Site.master and a content page for this master called Default.aspx.
Add the following code to the Default.aspx file:

<asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

If you try to run a simple ASPX page using a validator, the following exception will be thrown:

    "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)". Before fixing this, let's disable the unobtrusive validation to see the result.

On the page:

protected void Page_Load(object sender, EventArgs e)
{
   this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}

Now run the page and the validation will work as it used to work in ASP.Net 4.0 If you examine the rendered HTML, you will see that the gross inline script is rendered:

<script type="text/javascript">
//<![CDATA[
var Page_Validators =  new Array(document.getElementById("ContentPlaceHolder1_ctl00"));
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
var ContentPlaceHolder1_ctl00 = document.all ? document.all["ContentPlaceHolder1_ctl00"] : document.getElementById("ContentPlaceHolder1_ctl00");
ContentPlaceHolder1_ctl00.controltovalidate = "ContentPlaceHolder1_txt";
ContentPlaceHolder1_ctl00.errormessage = "txt is required";
ContentPlaceHolder1_ctl00.display = "Dynamic";
ContentPlaceHolder1_ctl00.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
ContentPlaceHolder1_ctl00.initialvalue = "";
//]]>
</script>


<script type="text/javascript">
//<![CDATA[

var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
       
document.getElementById('ContentPlaceHolder1_ctl00').dispose = function() {
    Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_ctl00'));
}
//]]>
</script>

Now let's re-enable the unobtrusive validation. In order to fix the previous exception, we need to install the following Nuget packages: (I like to install jQuery first to get the latest version, although this is not required.)

  1. jQuery
  2. ASPNET.ScriptManager.jQuery
  3. Microsoft.AspNet.ScriptManager.MSAjax
  4. Microsoft.AspNet.ScriptManager.WebForms

At this point, if you run the application again, the exception will be gone =) how cool eh?. This is because the following Nuget packages automatically register the scripts needed with the ScriptManager control.

Let's examine the code added by these Nuget packages using ILSpy:

AspNet.ScriptManager.jQuery

public static class PreApplicationStartCode
    {
        public static void Start()
        {
            string str = "1.8.1";
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
            {
                Path = "~/Scripts/jquery-" + str + ".min.js",
                DebugPath = "~/Scripts/jquery-" + str + ".js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "window.jQuery"
            });
        }
    }

Microsoft.AspNet.ScriptManager.MSAjax

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("MsAjaxBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/MsAjaxJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/MsAjaxBundle.js",
        LoadSuccessExpression = "window.Sys",
        CdnSupportsSecureConnection = true
    });
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjax.js", "window.Sys && Sys._Application && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxCore.js", "window.Type && Sys.Observer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxGlobalization.js", "window.Sys && Sys.CultureInfo");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxSerialization.js", "window.Sys && Sys.Serialization");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxComponentModel.js", "window.Sys && Sys.CommandEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxNetwork.js", "window.Sys && Sys.Net && Sys.Net.WebRequestExecutor");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxHistory.js", "window.Sys && Sys.HistoryEventArgs");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebServices.js", "window.Sys && Sys.Net && Sys.Net.WebServiceProxy");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxTimer.js", "window.Sys && Sys.UI && Sys.UI._Timer");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxWebForms.js", "window.Sys && Sys.WebForms");
    PreApplicationStartCode.AddMsAjaxMapping("MicrosoftAjaxApplicationServices.js", "window.Sys && Sys.Services");
}
private static void AddMsAjaxMapping(string name, string loadSuccessExpression)
{
    ScriptManager.ScriptResourceMapping.AddDefinition(name, new ScriptResourceDefinition
    {
        Path = "~/Scripts/WebForms/MsAjax/" + name,
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/" + name,
        LoadSuccessExpression = loadSuccessExpression,
        CdnSupportsSecureConnection = true
    });
}

Microsoft.AspNet.ScriptManager.WebForms

public static void Start()
{
    ScriptManager.ScriptResourceMapping.AddDefinition("WebFormsBundle", new ScriptResourceDefinition
    {
        Path = "~/bundles/WebFormsJs",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/4.5/6/WebFormsBundle.js",
        LoadSuccessExpression = "window.WebForm_PostBackOptions",
        CdnSupportsSecureConnection = true
    });
}

As you can see these Nuget packages automatically register the scripts using the ScriptManager object (besides installing the required JavaScript files)

Run the application and examine the rendered HTML. You will note that it's much cleaner now, in this case the inline script has been moved to an external file that can be rendered using bundles to increase performance. The rendered script looks like:

<script src="Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>

Much better right?. Notice how ASP.Net used HTML5 custom attributes:

<input name="ctl00$ContentPlaceHolder1$txt" type="text" id="ContentPlaceHolder1_txt" />
    <span data-val-controltovalidate="ContentPlaceHolder1_txt" data-val-errormessage="txt is required" data-val-display="Dynamic" id="ContentPlaceHolder1_ctl00" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="display:none;">*</span>
    <input type="submit" name="ctl00$ContentPlaceHolder1$ctl01" value="Send info" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ContentPlaceHolder1$ctl01&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" />

The data-val-* are custom attributes used by the unobtrusive validation engine

If you click the button to trigger the validation you will be pleased to see that it works as expected...but we are not done yet =/

The settings we have applied won't work if you intend to use an UpdatePanel control (yeah the evil UpdatePanel again...). This is because this control requires a ScriptManager control on the page (or MasterPage) and we do not have any yet. So let's add a simple ScriptManager control to the master page and see what happens. Add the following code to the Site.master page right under the <form...

<asp:ScriptManager runat="server" ID="scriptManager">
        </asp:ScriptManager>

Run the page again and fire the validation... oops... the client validation has gone =( We only have server validation. I'm not sure why this happens but my best guess is that the just added ScriptManager control is overriding our code settings.

To fix it, change the declaration of the ScriptManager control on the Site.master page to:

<asp:ScriptManager runat="server" ID="scriptManager1">
        <Scripts>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
        </Scripts>
    </asp:ScriptManager>

Run the application and our little example will work again as expected

Sadly these new settings are the equivalent to the settings added by code and we need to add them to be able to use the traditional Microsoft AJAX controls.

There's one last thing we need to configure, this is because there's actually a bug with the ValidationSummary control.

To test it, update the Default.aspx page as follows:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <asp:TextBox runat="server" ID="txt" />
    <asp:RequiredFieldValidator ErrorMessage="txt is required" ControlToValidate="txt" runat="server" Text="*" Display="Dynamic" />
    <asp:Button Text="Send info" runat="server" />

Now run the page again, scroll down until you can see the button and click it... woot your page jumped to the top... the workaround to solve this little bug is to add the following code to the Site.master

<script>
            window.scrollTo = function () {

            };
        </script>

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Add Multiple Files Utilizing ASP.NET 4.5

clock November 28, 2014 05:07 by author Ben

In earlier versions of ASP.NET (edition under ASP.NET 4.5), we didn't have any inbuilt functionality to add several files at the same time. ASP.NET FileUpload handle permits uploading just one file in a time. Alternate answers to add numerous files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to attain comparable performance.


In ASP.NET 4.5, we can add multiple documents simultaneously making use of ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 several attribute.

Under are the steps to add numerous information utilizing ASP.NET 4.5 :

  1. In Visual Studio 2012, In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:

<asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
</asp:fileupload>

In above code, I have set AllowMultiple property of FileUpload Control to true.

Add one button to upload multiple files using FileUpload Control on button click.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

Write below code on button click event handler.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (MultipleFileUpload.HasFiles)
        {
            StringBuilder UploadedFileNames = new StringBuilder();

            foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
            {
                string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                UploadedFileNames.AppendFormat("{0}<br />", FileName);
            }
            Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
        }
    }

On button click, I am checking for multiple files and saving those files into Files folder of web application.
Compile source code and run the website application.

 

I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder.



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: How to Bind Pages in ASP.NET

clock September 29, 2014 12:31 by author Kenny

How to Bind Pages in ASP.NET

ASP.NET is a unified Web development model that includes the services necessary for you to build enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET Framework, and when coding ASP.NET applications you have access to classes in the .NET Framework. You can code your applications in any language compatible with the common language runtime (CLR), including Microsoft Visual Basic and C#. These languages enable you to develop ASP.NET applications that benefit from the common language runtime, type safety, inheritance, and so on.

If you are familiar with classic ASP, the declarative data binding syntax introduced in ASP.NET will be familiar to you even though the functionality is vastly different. Data binding expressions are the code you see between <%# and %> characters in an ASPX file. The expressions allow you to easily bind controls to data sources, as well as properties, expressions, and results from method calls exposed by the page. While this feature is easy to use, it often causes some confusion about what is allowed and whether it should be employed.

Data binding basics

Data binding expressions link ASP.NET page properties, server control properties, and data sources when the page's DataBind method is called. You can place data binding expressions on the value side of an attribute/value pair in the opening tag of a server control or anywhere in the page. All data binding expressions, regardless of where you place them, must be contained between <%# and %> characters.

When used with data controls (like Repeater, DataGrid, and so forth), the expression parameter is usually a column name from the data source. However, as long as it returns a value, any valid expression may be used. Likewise, the same syntax may be used outside list controls. This includes displaying values on the page or populating control attributes.

Container.DataItem is a runtime alias for the DataItem bound to a specific item. It maps to an individual item from the data source—like one row from a database query or an individual element from an array. The actual data type for the DataItem is determined by the data source. So, if you're dealing with an array of integers, the DataItem will be an integer.

The following list provides a quick review of the VB.NET syntax for various scenarios:

<%# Container.DataItem %>--An array of string values is returned.
<%# Container.DataItem("expression") %>--The specific field from a DataView container is returned.

<%# Container.DataItem.PropertyName %>--The specific string property value of data source is returned.
<%# CStr(Container.DataItem.PropertyName) %>--Returns a property value converted to its string representation.

When you're using C#, the syntax is a bit different. The following list includes the corresponding C# code for each line in the previous list. Notice the basic syntax is the same, but it changes when property values are returned and converted to the appropriate data type.

<%# Container.DataItem %>
<%# ((DataRowView)Container.DataItem)["PropertyName"] %>
<%# ((ObjectType)Container.DataItem).PropertyName %>
<%# ((ObjectType)Container.DataItem).PropertyName.ToString() %>

Syntax is consistent when working with page level properties and methods. The syntax remains the same as long as string values are returned. The following list provides some examples:

<%# propertyName %>--The value for a page level property is returned.
<asp:ListBox id="lstValues" datasource='<%# propertyName %>' runat="server">--The value retrieved from the page level property (array, collection of objects, etc.) is bound to the data control.

<%# (objectName.PropertyName) %>--The value of the page level object property is displayed.
<%# MethodName() %>--The value returned from the page method is displayed.

You may use individual values (albeit properties, method return values, and so forth) on a page using the following syntax:
<%= Value %>

Using the Contain.DataItem object can be tedious, since you must be aware of the data type and convert it accordingly for use. Microsoft does provide the DataBinder class to further simplify development.

Working with DataBinder

Microsoft documentation (on MSDN) states the DataBinder class uses reflection to parse and evaluate a data binding expression against an object at runtime. This method allows RAD designers, such as Visual Studio .NET, to easily generate and parse data binding syntax. This method can also be used declaratively on a Web form's page to simplify casting from one type to another.

You can use the Eval method of the DataBinder class to make .NET do the heavy lifting when using data values in an ASP.NET page. The Eval method accepts the previously covered Container.DataItem object; it works hard to figure out the details of the field identified in the expression and displays it accordingly. It has the following syntax:

DataBinder.Eval(Container.DataItem, "field name", "optional formatting")

The DataBinder.Eval approach is great as it pushes work to the system. On the other hand, you should use it with caution, since time and resources are consumed as the system locates the element and determines its object/data type.

Plenty of options

Data binding makes it relatively simple to include data in ASP.NET pages. There are various data binding options available, which include: binding the data to a control and allowing it to decide how it is presented, or choosing declarative data binding to control presentation within the ASP.NET page. In the end, it comes down to your preference, but it is great to have options.

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



ASP.NET 4.5.2 Hosting with ASPHostPortal :: How to Publish and Deploy an ASP.NET Application in IIS

clock September 16, 2014 12:08 by author Kenny

Simple Way to Publish and Deploy an ASP.NET Application in IIS

ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. While Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

In this post, we will describe you how to publish and deploy your ASP.NET application in IIS. Actually it is so simple thing, you can publish your web application to the File System and copy paste all the files to your server. After that, you can add a new website from IIS. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

You can add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



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


 

Corporate Address (Location)

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

Tag cloud

Sign in