How to solve roslyn compiler issue on shared hosting?

Scenario:
I have created a web application using Visual Studio 2015 and .NET 4.6. When I have compiled and uploaded my project files to the hosting server, it showed the exception of related to permission. After checking for a while I found that application is trying to execute the CSC.exe file within the Bin\roslyn\ folder, but IIS user account does not permission to do that.

Solution:
If you are trying to publish Roslyn on shared hosting then you should know that it runs on Full Trust mode. Shared hosting companies does not allow Full Trust applications automatically , they override this globally with Medium Trust due to security restrictions as they are hosting multiple customers website and they don’t want one application affects another by any chance. Some hosting provider provide you the control to run your application on Full trust and provide setting to do that in these days.

Roslyn compilation will only work with Full Trust so on some shared hosting you might face challenges. I would suggest ask your hosting provider if they support Full Trust mode or not.

If shared hosting does not support Full Trust you should not deploy application with Roslyn, this will display you some sort of .exe file missing errors. Even you can’t upload .exe files to FTP on shared server, but you can somehow able to upload these exe files through their control using the zip package and then unzip on the hosting folder.

Below are the steps to deploy without Roslyn:

  1. Open NuGet Package Manager from tools menu or Use Manage NuGet Packages for Solution it will give you graphical way to uninstall packages from the solution project in which you are using that package.

    clip_image002_thumb[1]
  2. Now uninstall Microsoft.CodeDom.Providers.DotNetCompilerPlatform package using the below command line in Package Manager console:

    Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform <Your Web project name>

    clip_image004_thumb[2]
  3. Now rebuild & republish. This uninstallation also removes CodeDom configuration from web.config file. This will solve your purpose. Basically this will not generate any csc.exe, vbc.exe files inside bin folder of your project.

    In your web project publish profile settings, uncheck "Allow precompiled site to be updatable". You can find this under Settings > Precompile during publishing > configure.

    clip_image005_thumb[3]

Solution from - Roslyn CSC.exe, Web API 2 on Hosting Server
Hope this help others to solve the issue.
Cheers!

How to enable required field validator in a particular row of GridView?

Scenario:
In some cases editing is enabled on the selected row when you doing batch editing in ASP.NET GridView or DevExpress Grid Control. During edit operation we need to validate only these selected rows editor controls so that it will not block or validated another rows. It require to enable only associated cell validators in the editing rows.

Solution:

Let we have a checkbox in each row to select the editing row to enable the validator controls. Then we have to follow below steps:

First you need to add server event on Check Box control of Change event fire.

<asp:CheckBox ID="chkbox" runat="server" OnCheckedChanged="chkbox_CheckedChanged"    AutoPostBack="true"/>

Then fire of checked event of Checkbox you need to enable/disable RequiredFieldValidator server control.

protected void chkbox_CheckedChanged(object sender, EventArgs e)
{
   CheckBox chkbox= sender as CheckBox;
   GridViewRow currentRow = chkbox.NamingContainer as GridViewRow;
   RequiredFieldValidator rfv = grdCustomer.Rows[currentRow.RowIndex]
                                      .FindControl("ValReqED") as RequiredFieldValidator;
   if (chkCustomer.Checked)
   {
      rfv .Enabled = true;
   }
}

ASPX:

<asp:GridView ID="grdView" AutoGenerateColumns="false" BorderWidth="0" OnRowCommand="grdView_RowCommand" runat="server" CssClass="table">
    <Columns>
        <asp:TemplateField HeaderText="Save It">
            <ItemTemplate>
                <asp:CheckBox ID="chkbox" runat="server" AutoPostBack="true" OnCheckedChanged="chkbox_CheckedChanged"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Expiration Date">
            <ItemTemplate>
                <asp:TextBox ID="txtExpirationDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="ValReqExpD" Enabled="false" Display="Dynamic" runat="server" ErrorMessage="Expiry Date cannot be Blank." ControlToValidate="txtExpirationDate"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator Display="Dynamic" ID="ValRegExpD" runat="server" ControlToValidate="txtExpirationDate" ErrorMessage="Enter a valid Expiry Date ." ValidationExpression="([1-9]|0[1-9]|1[012])([-/.])([1-9]|0[1-9]|[12][0-9]|3[01])([-/.])(19[5-9][0-9]|20[0-4][0-9])">
                    <b>Enter a valid Renewal Date</b>
                </asp:RegularExpressionValidator><br />
                <asp:CompareValidator ID="ValCmpSD" Display="Dynamic" runat="server" ControlToCompare="txtEffectiveDate" ControlToValidate="txtExpirationDate" ErrorMessage="Expiry Date should be greater than Effective date" Operator="GreaterThan" Type="Date"></asp:CompareValidator>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

WCF or ASP.NET Web APIs for web services??

This is a interesting question for everyone and especially for me too. Whenever I got chance to dig for these technologies to create service, I found myself little confuse that which one should I choose.

It may be the “WCF vs ASP.NET Web API” contest for choosing in particular scenario and requirement of client. I got lots of reference and comparison related these two things which are discussed below:

The ASP.NET Web API is a continuation of the previous WCF Web API project (Conceptual changes are described on Codeplex WCF documentation - How to Migrate from WCF Web API to ASP.NET Web API).

Here is comparison from MSDN - WCF and ASP.NET Web API:
WCFvsWebAPI

ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.

In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

We can expose REST endpoints on WCF services as well.

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API.

Here are few nice articles and reference:
WCF or ASP.NET Web APIs? My two cents on the subject
Scott Hanselman’s - Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block

Configuring ASP.NET for sending Email

How ASP.NET Sends Mail

One of the most common uses of forms in a website is to send email. Sending email from a website used to be a complex and difficult task, but as with so many other tasks that used to be complex, ASP.NET makes sending email easy.

In this chapter you'll see two different classes from the .NET Framework used to send email with ASP.NET; the System.Net.SmtpClient class and the System.Net.MailMessage class.

The System.Net.SmtpClient Class

The SmtpClient class facilitates the sending of email with the Simple Mail Transfer Protocol or SMTP. The SmtpClient class is used to connect your ASP.NET application to the network (either the Internet or another network) and to authenticate you (if necessary) to the SMTP mail server.

We will use a few properties of the SmtpClient class to connect to the SMTP server on the network:

  • Host Property— The Host property is used to specify the name of the SMTP server to which you are connecting.

  • Port Property— Every connection on a network takes place over a specific channel on the network called a port. SMTP communication takes place on port 25 by default. The Port property defaults to a value of 25, but if your SMTP server requires a different port, you can specify that by using the Port property.

    Tip: It's uncommon for an SMTP server to not use port 25. Ask your network administrator, ISP, or hosting company if you're not sure what port your SMTP server uses.

  • Credentials Property— Most SMTP servers require that you provide a username and password or otherwise authenticate yourself before you can send email.

    Some SMTP servers (usually on corporate networks) allow you to use the credentials of the account running your ASP.NET code. In those cases, you can specify to use the default credentials, but in this web application, we'll specify a username and password.

The System.Net.MailMessage Class

The MailMessage class (as you've likely guessed) represents the actual message that is sent. The following list shows some of the properties of the MailMessage class, all of which should be self-explanatory:

  • To— The destination email address(es) for the message.

  • From— The email address of the sender.

  • Cc— The email address(es) that appear on the CC line.

  • Bcc— The email address(es) that appear on the BCC line.

  • Subject— The email's subject.

  • Attachments— A list of file attachments included with the email.

  • IsBodyHtml— A Boolean property that specifies whether or not the Body property uses HTML code.

  • Body The body of the email being sent. This is the actual text of the email message.

After you set the properties of the MailMessage class, you call the Send method and the SmtpClient class is used to send the message.

Modifying the Configuration File for internal Email Settings

In a real-world ASP.NET application, you may be sending email from many pages in your application. If the SMTP properties (such as server name, username, password, and so on) change, it's not efficient to have to make changes on each page that sends email.

Fortunately, many of the properties of the SmtpClient class can be specified in the configuration file for your ASP.NET application. If you specify properties in the configuration file, you have to modify only the configuration file if any of those properties change, and all pages that send email will automatically use the new settings.

Tip: If you specify a setting in your server-side code that's already been specified in your configuration file, the setting that you specify in code overrides the setting in the configuration file.

Adding Email Configuration to the web.config File

Mail configuration is specified in the <system.net> section of the web.config file. The web.config file doesn't contain a <system.net> section by default, so you need to add one.

Open the web application and then open the web.config file in Visual Web Developer. Add the following code to the web.config file directly before the opening <system.web> element:

<system.net>
    <mailSettings>
        <smtp>
            <network host="smtp.yourServer.com"
                     password="yourPassword"
                     userName="yourUsername" />
        </smtp>
    </mailSettings>
</system.net>

Tip: The settings you specify for your SMTP server are often the same settings you use in your email client for the outgoing mail server for your domain. Your hosting company probably has instructions for setting up email clients on their website that you can use to find settings for your configuration file.

Using the Web Site Administration Tool

You can also use the Web Site Administration Tool to configure your SMTP settings. The Web Site Administration Tool enables you to add and edit SMTP settings while minimizing the possibility of errors due to incorrect configuration or typographical errors.

Tip: When using the Web Site Administration Tool to configure SMTP settings, all entries are optional. If you don't provide a value for a required property in the configuration file, you need to provide it in your ASP.NET server-side code.

To use the Web Site Administration Tool to configure your SMTP settings, follow these steps:

1. Open your website and click the ASP.NET Configuration button at the top of the Solution Explorer window

2. Click the Application tab or the Application Configuration link in the Web Site Administration Tool.

3. Click the Configure SMTP Email Settings link on the Application page of the Web Site Administration Tool.

4. Enter your SMTP server name, as shown in Figure 1.

Figure 1. SMTP configuration can be modified on the Application tab of the Web Site Administration Tool.

 

5. Enter the port if necessary. In most cases, the default value of 25 should not be changed.

6. Enter an email address in the From text box if desired. The email address you enter here will show up as the sender of the email that ASP.NET sends.

7. Select an authentication method. Choose None if your SMTP server doesn't require authentication. Choose Basic if your SMTP server requires authentication that differs from the credentials of the account that your ASP.NET code is using. Choose NTLM if you want to use the credentials of the account running your ASP.NET code.

8. Click Save to save the configuration settings to the web.config file in your application.

After you click Save, the Web Site Administration Tool automatically updates your web.config file with the changes, and they take effect immediately.

What Happens When a Configuration File Is Saved

Every ASP.NET application runs inside a special area set aside in memory called an application domain. The purpose of the application domain is to provide isolation between different ASP.NET applications. The application domain ensures that one ASP.NET application doesn't access protected areas of another ASP.NET application.

When an application domain starts up, ASP.NET reads the information in the configuration file to set up the application domain. It then begins monitoring certain folders and files within the application for any changes. If a change is detected, ASP.NET shuts down the application domain and restarts it again so that any changes will take effect.

When you make a modification to the application's web.config file (whether by directly modifying the file or by modifying it indirectly with a tool such as the Web Site Administration Tool), ASP.NET immediately recycles the application pool so that the new configuration applies immediately to the application.

 

 

 

Sample Code to send Email in Asp.net without ASP.net web.config settings:

try
        {
            MailMessage msg = new MailMessage();

            msg.To.Add(toId);
            MailAddress frmAdd = new MailAddress(frmyahoo);
            msg.From = frmAdd;

            //Check user enter CC address or not
            if (ccId != "")
            {
                msg.CC.Add(ccId);
            }
            //Check user enter BCC address or not
            if (bccId != "")
            {
                msg.Bcc.Add(bccId);
            }
            msg.Subject = msgsubject;
            //Check for attachment is there
            if (FileUpload1.HasFile)
            {
                msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
            }
            msg.IsBodyHtml = true;
            msg.Body = mailContent;

            SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
            NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = NetCrd;
            mailClient.EnableSsl = false;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.Send(msg);

            clear();
            Label1.Text = "Mail Sent Successfully";
        }
        catch (Exception ex)
        {
            Label1.Text = "Unable to send Mail Please try again later";
        }
    }

Sample Code to send email in ASP.net with web.config with <mailsettings>

try
            {
                MailMessage mailMessage = new System.Net.Mail.MailMessage();
                mailMessage.To.Add(userEmailAddress);
                mailMessage.Subject = "Subject";
                mailMessage.Body = "Body Text";
                var smtpClient = new SmtpClient();
                smtpClient.Send(mailMessage);
                return "Mail send successfully";
            }
            catch (SmtpException ex)
            {
                return "Mail send failed:" + ex.Message;
            }

manual MailSettings for web.config

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="from@yourdomain.com">
        <network host="smtp server addresss" userName="username" password="password" 
          defaultCredentials="false" port="xxx" enableSsl="true"  />
      </smtp>
    </mailSettings>
  </system.net>

Displaying ASP GridView row index number

You can achieve this through two way:

Method 1

Step 1. Add this your GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
            DataSourceID="SqlDataSource1" OnRowCreated="GridView1_RowCreated" >

  <Columns>
            <asp:TemplateField HeaderText="RowId">
            <ItemTemplate><asp:Label runat="server" />                      
            </ItemTemplate>            
            </asp:TemplateField> 
...
</Columns>

Step 2: Add following GridView Event code snippet to your code – behind file (.cs)

protected void GridView1_RowCreated(object sender, 
			System.Web.UI.WebControls.GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) {
        // Retrieve the Label from the first column.
        Label myLabel = (Label)e.Row.Cells[0].Controls[0]; 

        // Set Label text equal to the rowIndex +1
        myLabel.Text = e.Row.RowIndex.ToString() + 1; 
    }
}

Method 2
The another way to do it is this one in the Columns section of your GridView control:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="5">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <%# Container.DataItemIndex + 1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
        </Columns>
    </asp:GridView>

Inline ASP.Net Tags, Code Render Blocks... (<%$, <%=, <%, <%#, etc.)

Code render blocks define inline code or inline expressions that execute when the page is rendered. There are two styles of code render blocks: inline code and inline expressions.
Use inline expressions as a shortcut for calling the Write method.

<% inline code %>
<%=inline expression %>

thee tags are evaluated during the Render portion of the page load cycle.

<% ... %>

The most basic inline tag, basically runs normal code:

<% if (User.IsInRole("admin")) { %> 
  You can see this 
<% } else { %> 
  You are no admin fool! 
<%} %>

http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx

 

<%= ... %>

Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable:

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>

http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

*note: <%= is the equivalent of Response.Write() .

 

<%# .. %>

Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<asp:Repeater ID="rptMeetings" DataSourceID="meetings" runat="server"> 
    <ItemTemplate> 
        <%# Eval("MeetingName") %> 
    </ItemTemplate> 
</asp:Repeater>

 

http://msdn2.microsoft.com/en-us/library/ms178366.aspx

 

<%$ ... %>

Used for expressions, not code; often seen with DataSources:

<asp:SqlDataSource ID="party" runat="server" ConnectionString="<%$ ConnectionStrings:letsParty %>" SelectCommand="SELECT * FROM [table]" />

http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx

 

<%@ ... %>

This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> 
<%@ Register TagPrefix="wp" Namespace="CustomWebParts" %>

http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx

 

<%-- ... --%>

This is a server side comment, stuff you don't want anyone without code access to see:

    <asp:Label ID="lblAwesome" runat="server" /> 
    <%-- sometimes end users make me angry --%> 
    <asp:LinkButton ID="lbEdit" Text="Edit" OnClick="Edit_Click" runat="server" />

http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx

How User Controls Are Processed

The HTML portion of ASP.NET Web pages can contain a mix of Web controls, user controls, and HTML syntax. When an ASP.NET Web page is visited for the first time, or for the first time after a change has been made to the HTML portion of the Web page, a class is automatically created from the HTML portion. This class, which is derived from the Web page's code-behind class, constructs the Web page's control hierarchy based on the declarative syntax in the HTML portion.

For example, imagine that a Web page had the following markup in its HTML portion:

<html>
<body>
<form runat="server">

Name: <asp:TextBox runat="server" id="name"></asp:TextBox>
<br />
<asp:Button runat="server" Text="Submit"></asp:Button>

</form>
</body>
</html>

 

This would generate the following control hierarchy:

 

Figure 2. Controls hierarchy on page

Notice that the HTML markup is converted into LiteralControl instances, the Web Form into an HtmlForm object, and the TextBox and Button Web controls into their respective classes.

Once this control hierarchy is created, the ASP.NET Web page can be rendered by recursively invoking the RenderControl(HtmlTextWriter) method of each of the controls in the hierarchy. When a control's RenderControl(HtmlTextWriter) method is invoked, the control generates its HTML markup and appends it to the HtmlTextWriter object. Realize that each time an ASP.NET Web page is requested, the page's corresponding class is invoked causing the control hierarchy to be created and rendered.

User controls work in a similar fashion to ASP.NET Web pages. When a user control is visited for the first time, or for the first time after the HTML portion has been changed, the user control is compiled into a class that is derived from the user control's code-behind class. Like the ASP.NET Web page's autogenerated class, the user control's autogenerated class constructs a control hierarchy based on the HTML portion of the user control. In essence, a user control has its own control hierarchy.

Imagine, then, that we had a user control with the following HTML markup:

<asp:Label runat="server" id="lblCategoryName"></asp:Label>

<br />

<asp:Label runat="server" id="Description"></asp:Label>

The user control's control hierarchy, then, would look like the following:

 

 

 

Figure 3. Control Hierarchy for user control

Recall that an ASP.NET Web page's HTML portion can contain not only Web controls and HTML syntax, but user controls as well. user controls are entered into the control hierarchy as an instance of the user control's auto generated class. So, imagine we augmented our previous ASP.NET Web page example so that after the Button Web control was an instance of the user control whose declarative syntax we just discussed. This would cause the Web page's control hierarchy to look like the following:

Figure 4. Updated control hierarchy for page

After the user control class is added to the control hierarchy, the class's InitializeAsUserControl(Page) method is invoked. The InitializeAsUserControl(Page) method is defined in the System.Web.UI.UserControl class, which the autogenerated user control class is derived from indirectly. (Recall that the autogenerated user control class is derived from the user control's code-behind class; this code-behind class is derived from System.Web.UI.UserControl, similar to how an ASP.NET Web page's code-behind class is derived from System.Web.UI.Page.) The InitializeAsUserControl(Page) method generates the user control's class hierarchy and assigns the user control's Page property to the passed in Page instance, thereby allowing the user control to programmatically reference the Page to which it belongs. After InitializeAsUserControl(Page) runs, the Web page's control hierarchy looks like:

 

Figure 5. Updated page hierarchy after initializing the user control

Notice that once the user control is affixed to the control hierarchy and builds up its own control hierarchy, the page's control hierarchy appears just as it would if a user control hadn't been used, but instead had its HTML portion entered directly into the page's HTML portion. With this complete hierarchy, the Web page can be rendered by recursively calling the RenderControl(HtmlTextWriter) method of each control in the hierarchy.

Now that we've seen how a user control is handled underneath the covers, let's take a look at some of the more advanced concepts of user controls, starting with how to respond to events raised by Web controls in a user control.

 

Failed to access IIS metabase.

Scenario:-
I have windows XP Professional installed on my machine and I got this error after
configuration of my virtual directory on IIS.

Server Error in '/myweb' Application.


Failed to access IIS metabase.

Description: An unhandled exception occurred during the execution of the current web request. Please review
the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.
The process account used to run ASP.NET must have read access to the IIS metabase
(e.g. IIS://servername/W3SVC). For information on modifying metabase permissions,
please see http://support.microsoft.com/?kbid=267904.

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.

Stack Trace:

[HostingEnvironmentException: Failed to access IIS metabase.]   
System.Web.Configuration.MetabaseServerConfig.MapPathCaching(String siteID, VirtualPath path) +1076   
System.Web.Configuration.MetabaseServerConfig.System.Web.Configuration.IConfigMapPath2.MapPath(String siteID, VirtualPath vpath) +9  
System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull) +301   System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath, Boolean permitNull) +51   
System.Web.CachedPathData.GetPhysicalPath(VirtualPath virtualPath) +39 
System.Web.CachedPathData.GetConfigPathData(String configPath) +704 
System.Web.CachedPathData.GetConfigPathData(String configPath) +583
System.Web.CachedPathData.GetApplicationPathData() +38  
System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) 8778063
System.Web.Configuration.RuntimeConfig.GetConfig(VirtualPath path) +46   
System.Web.Configuration.RuntimeConfig.GetLKGRuntimeConfig(VirtualPath path) +96

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

Solution :-

This Error Caused Because You Not Have Register ASP.Net with IIS.
Please Follow Following Step to Regiser ASP.Net With IIS.

-> Go to Start - >  Run -> Cmd.

-> GO to Your System Drive Mostly C Drive.

-> Type C:\WINDOWS\Microsoft.NET\Framework\<your framework version directory>\aspnet_regiis -i

Just wait And Message comes Successfully Register.

Or you go to your visual studio command prompt in visual studio tools and run the same command

aspnet_regiis –i


clip_image002

A potentially dangerous Request.Form value was detected from the client

Server Error in '/' Application.

 

A potentially dangerous Request.Form value was detected from the client (txtCode="<br/>").

Description: Request Validation has detected a potentially dangerous client input value, and processing of
the request has been aborted. This value may indicate an attempt to compromise the security of your application,
such as a cross-site scripting attack. To allow pages to override application request validation settings, set the
requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0".

Example: <httpRuntime requestValidationMode="2.0" />. After setting this value, you can then disable request
validation by setting validateRequest="false" in the Page directive or in the <pages> configuration section.
However, it is strongly recommended that your application explicitly check all inputs in this case. For more
information, see http://go.microsoft.com/fwlink/?LinkId=153133.

Exception Details:System.Web.HttpRequestValidationException: A potentially dangerous Request.Form
value was detected from the client (txtCode="<br/>").
 
You have to do little modification to you application to get this fixed.

  1. Add <httpRuntime requestValidationMode="2.0" /> in your application web.config
       under <system.web>.
       <system.web>
        <httpRuntime  requestValidationMode="2.0"/>
  2. Add RequestValidation="false" on your page or in web.config <pages>
       attribute.
    <%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false"
     
    or
    to work this for whole application do in web.config as:
    <system.web>
        <httpRuntime  requestValidationMode="2.0"/>
        <pages validateRequest ="false"></pages>

Securing ASP.Net pages - ASP.NET - Forms Authentication

ASP.Net has a built-in feature called forms authentication which allows developers to easily get certain areas of a website. In this post I will create a simple authentication example using C # and ASP.Net 4.0 (still in beta after the posting date).
The security settings with ASP.Net is configured from the web.config file. This is a standard ASCII file, an XML format, which is at the root of the web application. This is a sample web.config file:

<configuration>
    
<system.web>
        
<authentication mode="Forms">
            
<forms name ="TestAuthCookie" loginUrl="login.aspx" timeout="30">
                
<credentials passwordFormat="Clear">
                    
<username="user1"password="pass1"/>
                    
<username="user2"password="pass2"/>
               
</authentication>
        
<authorization>
            
<denyusers="?"/>
       
</authorization>
        
<compilation targetFramework="4.0"/>
        
<pages controlRenderingCompatibilityVersion="3.5"clientIDMode="AutoID"/>
    

</system.web>
 </configuration>

 
The first line is the standard for a web.config file and not related to security.
 
The following section specifies that you are configuring security for this web application. First, set the authentication mode to use a cookie in this specific example. You can specify a unique name for your cookie. This section also specifies the page or URL that contains the authentication code (login.aspx in this case) and the duration of the authentication cookie should be stored.
The next two lines specify the user names and passwords are valid for this web application. As far as I know there is no limit on the number of user accounts can be placed in the web.config, but if there were a large number - or if they change frequently - it might be best to put this information in an external file as a database or an XML file instead (I'll show this in a future article).
Now that we've identified some accounts valid login is necessary to specify in reality we want to password protect. For this example I decided to password protect the entire site from the root, so the optional attribute is not used. We have established the authority to deny all unauthenticated users (deny users ="?").
That's all it takes to file config.web. If someone tries to access the page and the user is not authenticated and will be redirected to login.aspx page.
This is only half the process required however. Now we have to create the login.aspx page to actually authenticate the user for our application.
Here is the complete source code for the login.aspx page shows:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "login.aspx.cs"%>
 
DOCTYPE html PUBLIC "- / / W3C / / DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> </title>
<head>
<body>
  <form  id="Form1" runat="server">
    <div>
        Username:
    <asp:TextBox    ID="txtUsername" <asp:TextBox runat="server"> 
        <br />
        Password:
   <asp:TextBox    ID="txtPassword" <asp:TextBox runat="server">
        <br />
       <asp:Button Text="Login" onclick="Button1_Click" ID="Button1"  runat="server" />
        <br />
        <br />
       <asp:Label runat="server" ID="lblStatus" Text="Please  login"> </asp:Label>
    </div>
    </form>
</body>
</html>
using System;
using System.Web.UI.WebControls;
using System.Web.Security;
 
public partial class Default3: System.Web.UI.Page
{
    protected void Button1_Click (object sender, EventArgs e)
    {
        if (FormsAuthentication.Authenticate (txtUsername.Text, txtPassword.Text))
        {
            lblStatus.Text = ("Welcome" + txtUsername.Text);
            FormsAuthentication.RedirectFromLoginPage (txtUsername.Text, true);
        }
        more
        {
            lblStatus.Text = "Invalid login";
        }
 
    }
}