ASP.NET Error: ASP.NET 4.0 has not been registered on the web server

Problem:

asp1

 

Solution:

To resolve ‘ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly’ error when opening a solution we can:

  1. Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click ‘Turn Windows Featrues on. Then in the IIS –> WWW servers –> App Dev Features ensure that ASP.NET is checked.
  2. enter image description hereAnd run the following cmd line to install, C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

 

ASP.NET: Send mail html format – Email settings for godday hosting

  1. It is always better to check email settings with godaddy technical support.
  2. You have to use the following relay server as the mail server: relay-hosting.secureserver.net
  3. You do not need to provide any user name & password for this relay server but you need an valid from email address. You have to use default credentials:smtp.UseDefaultCredentials = true; 
  4. You have to turn off ssl connection as it does not support secure connection: smtp.EnableSsl = false;
asp.net web.config file settings:
<appSettings>
    <!–email hosting for godaddy website–>
    <add key=MailServer value=relay-hosting.secureserver.net/>
    <add key=Port value=25/>
    <!–godaddy hosting does not need username & password–>
    <!–
    –>
    <add key=FromMail value=masuds_mail@yahoo.com/>
    <add key=SendToMail value=info@ete-consulting.co.uk />
  </appSettings>
 
  <system.web>
    <!–custome error mode need to be off or remote only–>
    <customErrors mode=Off/>
    <!–asp.net c# web application shows error:
    The application attempted to perform an operation not allowed by the security policy. 
    To grant this application the required permission please contact your system administrator or
    change the application’s trust level in the configuration file. –>
    <trust level=Full originUrl=“”/>
   

config.cs class file:
public static string SendMail(string subject, string body)
    {
        //function: send html email using asp.net c#
        SmtpClient smtp = new SmtpClient();
        smtp.Host = Config.MailServer;
        smtp.Port = Config.Port;
        //credentials need to set to true for godaddy hosting
        smtp.UseDefaultCredentials = true;
        //godaddy does not support Secure connection
        smtp.EnableSsl = false;
        //smtp.Credentials = new System.Net.NetworkCredential(Config.UserName, Config.Password);
        MailMessage mailMsg = new MailMessage();
        mailMsg.To.Add(Config.SendToMail);
        mailMsg.From = new MailAddress(Config.FromMail);
        mailMsg.Subject = subject;
        mailMsg.Body = body;
        //send html email message.
        //you will be able to use html tag in the message to
        mailMsg.IsBodyHtml = true;
        string msg = null;
        try
        {
            smtp.Send(mailMsg);
        }
        catch (Exception ex)
        {
            msg = ex.Message;
            //throw ex;
        }
        return msg;
    }
aspx.cs coding to send email html formatted
protected void btnStartProject_Click(object sender, EventArgs e)
    {
        //in order to be able to see the html elements in aspx.cs use the runat=”server” attribute
        string message, subject, body, name, gender;
        subject = slProjectType.Value;
        name = firstName.Value + ” “ + lastName.Value;
        if (male.Checked == true)
            gender = “Male”;
        else
            gender = “Female”;
       
       
        body =

Dear sir,

            +

I am interested to start a “

            + slProjectType.Value
            + ” with your company http://www.ete-consulting.co.uk

            +

My personal details:

            +

First name: “

            + firstName.Value
            +

Last name: “

            + lastName.Value
            +

Gender: “

            + gender
            +

My country: “

            + slCountrySelector.Value
            +

My contact details

            +

mobile: “

            + telephone.Value
            +

email: “

            + email.Value
            +

Project details

            +

Project type: “

            + slProjectType.Value
            +

Here is my project details (Message from the customer): “

            + txtProjectBrief.Value
            +

Thank you

            + name
            ;
        //call the email function
        message = Config.SendMail(subject, body);
       
        if (message == null)
            lblMessage.InnerText = “Email sent succefully.”;
        else
            lblMessage.InnerText = “Sorry, your email was not sent to the sender. Please try again.”;
       
        //show the email successfull message
        lblMessage.InnerHtml = message;
    }
Troubleshoot godaddy website error messages
If the MailServer host name is wrong it shows error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 202.xx.xx.xx:80
If the user credentials are used, it shows error:
the remote certificate is invalid according to the validation procedure
If EnableSsl is used it shows error:
server does not support secure connection

ASP.NET Error: Web hosting error, Request for the permission of type ‘System.Security

Scenario:
I have created a web app using visual studio 2013 and it was showing error message

Server Error in '/' Application.
--------------------------------------------------------------------------------

Security Exception 
Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. 

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  
 
Solution:
In web.config adding the following line worked for me:

   
 

ASP.NET Error: The type "xxxx…." user control exists in both folder

Just change the web.config file as followed:
<compilation debug=false targetFramework=4.0 batch=false />
Add the batch=”false” attribute to the “compilation” element of the web.config file.
This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.

ASP.NET: How to: Prepare to Deploy a Web Project

How to: Prepare to Deploy a Web Project

Before you deploy or redeploy a Web project, you might want to prevent the production site from responding to page requests during the deployment process. This can help avoid errors that might result during the time when the changes are only partially completed. Also, when changes occur to some file types and folders, the application domain restarts, and you might want to make sure that this does not happen multiple times.

To take a Web application offline before deployment

  1. Create a file called App_offline.htm and include a message in the file that lets users know that the site is unavailable because you are updating the site.
  2. Place the App_offline.htm file in the root folder of the target Web site.
    While the App_offline.htm file exists in the root of your Web site, any request to the Web site will redirect to that file.
    When you have finished deploying the site, remove the App_offline.htm file.
Basic Deployment Tasks 
Here are the basic tasks that you have to do in order to deploy to a third-party hosting company:
  1. Set up an account with a hosting company.
    For information about hosting providers that support automated deployment from Visual Studio, see ASP.NET Hosting. Make sure that you choose a provider that supports the version of ASP.NET that your web project targets.
  2. Create a publish profile.
    A publish profile specifies the server you are deploying to, credentials for logging on to the server, databases to deploy, and other options. The hosting company sends you the settings you need for the publish profile, either in an email or in a file that you can import into Visual Studio.
  3. Start the deployment process by clicking the one-click publish button. The Publish button is in the Publish Web wizard that you use to create publish profiles. It is also available in the Web One Click Publish toolbar that you can choose from the ViewToolbars menu in Visual Studio.

How to make an Website Offline:

  1. Create a file called App_Offline.htm
  2. Insert a offline message you want to display while the website is offline
  3. Upload that file into the webhost root folder
  4. If the App_Offline.htm file is present website automatically redirect it to this file
  5. To make the Website online again just remove the App_offline.htm file.

Taking an Application Offline before Publishing


In Web Deploy V3, we added support to automatically take an ASP.Net application offline before publishing to it. This is useful if a user wants to ensure that their application does not have a lock on a file (e.g. SQL CE sdf files which only allow one connection to the file at a time) being overwritten, or if they want to ensure that visitors to their site cannot affect the publish process. The way it works is if Web Deploy detects that a change needs to be made on the destination server, it will automatically drop a blank App_Offline.htm file into the root of the application folder. When ASP.Net detects that a file by the name of “App_Offline.htm” exists, it will automatically bring down the app domain hosting the application. When the publish process is completed, the App_Offline.htm file will be removed and the site will be online again.

  • Enabling Application Offline

Web Deploy takes an application offline by using the “AppOffline” rule, which is off by default. If a client wishes to turn it on during a publish operation, it simply needs to enable the rule. Here is an example of how to do this from the command line (executable lives under “%programfiles%\IIS\Microsoft Web Deploy V3”):
msdeploy.exe -verb:sync -source:iisApp=mySite -dest:auto,computername=<publishUrl> -enableRule:AppOffline 

  • What happens when a publish fails

If an error occurred during publishing, the htm file will remain in the site root to keep it offline because it is now in an unknown state. After fixing your publishing issue, you will need to bring the application back online. To do this, you can either manually delete the App_Offline.htm file from your application root on the server, or republish your site. Here is an example of how to delete the App_Offline.htm file from the command line:
msdeploy.exe -verb:delete -dest:contentPath=siteName/App_Offline.htm,computername=<publishUrl> 

Precompiling for Deployment Only

When you precompile for deployment only, the compiler produces assemblies from virtually all ASP.NET source files that are normally compiled at run time. This includes program code in pages, .cs and .vb class files, other code files, and resource files. The compiler removes all source and markup from the output. In the resulting layout, compiled files are generated for each of the .aspx files (with the extension .compiled) that contain pointers to the appropriate assembly for that page.
To change the Web site, including the layout of pages, you must change the original files, recompile the site, and redeploy the layout. The only exception is the site configuration; you may make changes to the Web.config file on the production server without having to recompile the site.
This option provides the greatest degree of protection for your pages and the best performance at startup.

How to Create an Offline Web Page

Web designers commonly have a need to build pages when offline in order to continue work when an Internet connection is not available. By working on a website offline, you can test new concepts prior to going live on the Internet, thereby avoiding any loss of web traffic. Additionally, an offline website provides a full backup of your website in the event of catastrophic failure with the copy saved on your web server. Have a question? Get an answer from Online Tech Support now!

Instructions

    • 1
      Create a directory structure on your computer that is identical to your web server. To do this, create a folder on your computer named “MyWebsite”. Then, open the “MyWebsite” folder and create the first level of sub-folders that exist on your website, such as “mycontent” and “images”. To create a new folder, right-click in the white space of the folder, left-click “New Folder” and type the name of the website in the text field.
    • 2
      Save copies of all of the images on your website to the “Images” folder located under the “MyWebsite” folder created in step 1.
    • 3
      Change the hyperlinks of the images in your web pages to be directed to the local folder. For example, where your previous image link URLs would be similar to: “http://www.mywebsite.com/images/myimage.jpg&#8221;, the new URL’s will be of the form: “images/myimage.jpg”.
    • 4
      View the offline website in your web browser by using your browser’s file chooser to open the “Index.html” page, or manually enter the following URL convention in your browser’s toolbar:
      “file:///c:/MyWebsite/Index.html”.


Publishing a Visual Studio Project (Not Website):

To access this tab on the Properties page

  1. In Visual Studio, open a web application project.
  2. In Solution Explorer, open the shortcut menu and choose Properties (C#) or MyProject (Visual Basic) to display the Properties page.
Choose the Package/Publish Web tab.
Package/Publish dialog box
Note: 
  1. Create a Web Deployment Package in Visual Studio

ASP.NET: Currency Conversion, Using Google API

Create new web site in Visual Studio. In Default.aspx page we need to jQuery library (you can download it from jquery.com), so add:
Add to page body the following html code:
   

        Amount: 
       
   
   

        From: 
       
            United Arab Emirates Dirham (AED)
            Netherlands Antillean Guilder (ANG)
            Argentine Peso (ARS)
            Australian Dollar (AUD)
            Bangladeshi Taka (BDT)
            Bulgarian Lev (BGN)
            Bahraini Dinar (BHD)
            Brunei Dollar (BND)
            Bolivian Boliviano (BOB)
            Brazilian Real (BRL)
            Botswanan Pula (BWP)
            Canadian Dollar (CAD)
            Swiss Franc (CHF)
            Chilean Peso (CLP)
            Chinese Yuan (CNY)
            Colombian Peso (COP)
            Costa Rican Colón (CRC)
            Czech Republic Koruna (CZK)
            Danish Krone (DKK)
            Dominican Peso (DOP)
            Algerian Dinar (DZD)
            Estonian Kroon (EEK)
            Egyptian Pound (EGP)
            Euro (EUR)
            Fijian Dollar (FJD)
            British Pound Sterling (GBP)
            Hong Kong Dollar (HKD)
            Honduran Lempira (HNL)
            Croatian Kuna (HRK)
            Hungarian Forint (HUF)
            Indonesian Rupiah (IDR)
            Israeli New Sheqel (ILS)
            Indian Rupee (INR)
            Jamaican Dollar (JMD)
            Jordanian Dinar (JOD)
            Japanese Yen (JPY)
            Kenyan Shilling (KES)
            South Korean Won (KRW)
            Kuwaiti Dinar (KWD)
            Cayman Islands Dollar (KYD)
            Kazakhstani Tenge (KZT)
            Lebanese Pound (LBP)
            Sri Lankan Rupee (LKR)
            Lithuanian Litas (LTL)
            Latvian Lats (LVL)
            Moroccan Dirham (MAD)
            Moldovan Leu (MDL)
            Macedonian Denar (MKD)
            Mauritian Rupee (MUR)
            Maldivian Rufiyaa (MVR)
            Mexican Peso (MXN)
            Malaysian Ringgit (MYR)
            Namibian Dollar (NAD)
            Nigerian Naira (NGN)
            Nicaraguan Córdoba (NIO)
            Norwegian Krone (NOK)
            Nepalese Rupee (NPR)
            New Zealand Dollar (NZD)
            Omani Rial (OMR)
            Peruvian Nuevo Sol (PEN)
            Papua New Guinean Kina (PGK)
            Philippine Peso (PHP)
            Pakistani Rupee (PKR)
            Polish Zloty (PLN)
            Paraguayan Guarani (PYG)
            Qatari Rial (QAR)
            Romanian Leu (RON)
            Serbian Dinar (RSD)
            Russian Ruble (RUB)
            Saudi Riyal (SAR)
            Seychellois Rupee (SCR)
            Swedish Krona (SEK)
            Singapore Dollar (SGD)
            Slovak Koruna (SKK)
            Sierra Leonean Leone (SLL)
            Salvadoran Colón (SVC)
            Thai Baht (THB)
            Tunisian Dinar (TND)
            Turkish Lira (TRY)
            Trinidad and Tobago Dollar (TTD)
            New Taiwan Dollar (TWD)
            Tanzanian Shilling (TZS)
            Ukrainian Hryvnia (UAH)
            Ugandan Shilling (UGX)
            US Dollar (USD)
            Uruguayan Peso (UYU)
            Uzbekistan Som (UZS)
            Venezuelan Bolívar (VEF)
            Vietnamese Dong (VND)
            CFA Franc BCEAO (XOF)
            Yemeni Rial (YER)
            South African Rand (ZAR)
            Zambian Kwacha (ZMK)
        to:
            United Arab Emirates Dirham (AED)
            Netherlands Antillean Guilder (ANG)
            Argentine Peso (ARS)
            Australian Dollar (AUD)
            Bangladeshi Taka (BDT)
            Bulgarian Lev (BGN)
            Bahraini Dinar (BHD)
            Brunei Dollar (BND)
            Bolivian Boliviano (BOB)
            Brazilian Real (BRL)
            Botswanan Pula (BWP)
            Canadian Dollar (CAD)
            Swiss Franc (CHF)
            Chilean Peso (CLP)
            Chinese Yuan (CNY)
            Colombian Peso (COP)
            Costa Rican Colón (CRC)
            Czech Republic Koruna (CZK)
            Danish Krone (DKK)
            Dominican Peso (DOP)
            Algerian Dinar (DZD)
            Estonian Kroon (EEK)
            Egyptian Pound (EGP)
            Euro (EUR)
            Fijian Dollar (FJD)
            British Pound Sterling (GBP)
            Hong Kong Dollar (HKD)
            Honduran Lempira (HNL)
            Croatian Kuna (HRK)
            Hungarian Forint (HUF)
            Indonesian Rupiah (IDR)
            Israeli New Sheqel (ILS)
            Indian Rupee (INR)
            Jamaican Dollar (JMD)
            Jordanian Dinar (JOD)
            Japanese Yen (JPY)
            Kenyan Shilling (KES)
            South Korean Won (KRW)
            Kuwaiti Dinar (KWD)
            Cayman Islands Dollar (KYD)
            Kazakhstani Tenge (KZT)
            Lebanese Pound (LBP)
            Sri Lankan Rupee (LKR)
            Lithuanian Litas (LTL)
            Latvian Lats (LVL)
            Moroccan Dirham (MAD)
            Moldovan Leu (MDL)
            Macedonian Denar (MKD)
            Mauritian Rupee (MUR)
            Maldivian Rufiyaa (MVR)
            Mexican Peso (MXN)
            Malaysian Ringgit (MYR)
            Namibian Dollar (NAD)
            Nigerian Naira (NGN)
            Nicaraguan Córdoba (NIO)
            Norwegian Krone (NOK)
            Nepalese Rupee (NPR)
            New Zealand Dollar (NZD)
            Omani Rial (OMR)
            Peruvian Nuevo Sol (PEN)
            Papua New Guinean Kina (PGK)
            Philippine Peso (PHP)
            Pakistani Rupee (PKR)
            Polish Zloty (PLN)
            Paraguayan Guarani (PYG)
            Qatari Rial (QAR)
            Romanian Leu (RON)
            Serbian Dinar (RSD)
            Russian Ruble (RUB)
            Saudi Riyal (SAR)
            Seychellois Rupee (SCR)
            Swedish Krona (SEK)
            Singapore Dollar (SGD)
            Slovak Koruna (SKK)
            Sierra Leonean Leone (SLL)
            Salvadoran Colón (SVC)
            Thai Baht (THB)
            Tunisian Dinar (TND)
            Turkish Lira (TRY)
            Trinidad and Tobago Dollar (TTD)
            New Taiwan Dollar (TWD)
            Tanzanian Shilling (TZS)
            Ukrainian Hryvnia (UAH)
            Ugandan Shilling (UGX)
            US Dollar (USD)
            Uruguayan Peso (UYU)
            Uzbekistan Som (UZS)
            Venezuelan Bolívar (VEF)
            Vietnamese Dong (VND)
            CFA Franc BCEAO (XOF)
            Yemeni Rial (YER)
            South African Rand (ZAR)
            Zambian Kwacha (ZMK)
Now, we have input field to type amount and two drop downs with currencies and button to call web service function which calculate the differences of currencies and fill result in div with name “results”.
Now add jQuery code to handle button event to call web service and filling result data vie AJAX:
$(document).ready(function() {
    $(‘#submit’).click(function() {
        var amount = $(‘#a’).val();
        var from = $(‘#from’).val();
        var to = $(‘#to’).val();
        var params = “http://www.google.com/finance/converter?a=&#8221; + amount + “&from=” + from + “&to=” + to;
 
        $.ajax({ type: “POST”,
            url: “WebService.asmx/Convert”,
            data: “{amount:” + amount + “,fromCurrency:'” + from + “‘,toCurrency:'” + to + “‘}”,
            contentType: “application/json; charset=utf-8”,
            dataType: “json”,
            success: function(data) {
                $(‘#results’).html(data.d);
            }
        });
    });
});
Add Reference into WebService.cs file:
using System.Web.Script.Services;
[ScriptService]

Then, the last thing to do is create web service and declare function which take three parameter (Amount, From Currency, To Currency) and return the decimal.
 
[WebMethod]
public decimal Convert(decimal amount, string fromCurrency, string toCurrency)
{
    WebClient web = new WebClient();
    string url = string.Format(“http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}”, fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
    string response = web.DownloadString(url);
    Regex regex = new Regex(“rhs: \\\”(\\d*.\\d*)”);
    decimal rate = System.Convert.ToDecimal(regex.Match(response).Groups[1].Value);
    return rate;
}
Complete WebService.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Script.Services;
///
/// Summary description for WebService
///

 

[WebService(Namespace = http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    public WebService () {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
    [WebMethod]
    public stringHelloWorld() {
        return “Hello World”;
    }
    [WebMethod]
    public decimalConvert(decimal amount, string fromCurrency, stringtoCurrency)
    {
        WebClient web = newWebClient();
        string url = string.Format(http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}”, fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
        string response = web.DownloadString(url);
        Regex regex = new Regex(“rhs: \\\”(\\d*.\\d*)”);
        decimal rate = System.Convert.ToDecimal(regex.Match(response).Groups[1].Value);
        return rate;
    }
}

Note:
The getJSON() method is used to get JSON data using an AJAX HTTP GET request.
$(selector).getJSON(url,data,success(data,status,xhr))

url
Required. Specifies the url to send the request to
data
Optional. Specifies data to be sent to the server
success(data,status,xhr)
Optional. Specifies the function to run if the request succeeds
Additional parameters:
  • data – contains the data returned from the server.
  • status – contains a string containing request status (“success”, “notmodified”, “error”, “timeout”, or “parsererror”).
  • xhr – contains the XMLHttpRequest object
Good news is here – Google have a secrete API for Currency Conversion. Its a simple open API you can use for all type of foreign currencies.
How to use it?
If you want currency converter £ to dollars, use it like this –
If you want to calculate currency converter $ to £ –
You can change value of input currency, for example you want to know the value for $100 in India Rupees

Two links:

Troubleshoot:
  • I did not use the using.system.web.script.services; and [Services] reference and it did not work. After adding the reference it has worked properly.

ASP.NET: DataList, Add item Programmatically

Default.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        Test
    
    
        <form id="frmTest" runat="server">
            <asp:DataList ID="dlTest" runat="server">
                
                    <%#DataBinder.Eval(Container, "DataItem")%>
                
            
        
    
Default.aspx.vb
Partial Class Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim strTest() As String = {"No data"}
            dlTest.DataSource = strTest
            dlTest.DataBind()
        Catch exMessage As Exception
            Response.Write("<!-- Error D001: " + exMessage.Message + ControlChars.NewLine + exMessage.StackTrace + "-->" & ControlChars.NewLine)
        End Try
    End Sub
End Class
This show the “No data” text in the DataList, but i recommend you to use a Label instead of the DataList, when the DataSet is empty, hide the DataList and show the Label with the text that you want to show.