European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 4.5 Hosting - HostForLIFE.eu :: Secure Your Website No Copy Paste

clock June 2, 2016 20:43 by author Anthony

Have you ever worked really hard on graphics for your site only to find later that someone has stolen them as their own. You can help encrypt and protect your site with the following codes. No right click block is 100% effective, but they will help against novices.

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:



HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 4.5.1 Germany Hosting - HostForLIFE.eu :: ASP.NET Session and Concurrent Access

clock March 5, 2014 05:35 by author Peter

In one of my projects I found some a strange at first sight issue related to concurrent Session usages. During one long request the other parallel requests were waiting until the previous one is finished.This issue occurs when user tries to download file from ashx-handler. Handler requires Session to get some user-related configuration which is stored there. I've tried to dig deeper and that what I've found. By default no concurrent access to the asp.net session state is allowed. Requests with same SessionID will be locked exclusively to prevent potential corruption of its state. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try HostForLife.eu

When you have request1 `in progress` and trying to do request2 - Session object will be locked by request1 and our code in request2 will be waiting for request1 completed. ASP.NET Session is thread safe and synchronization mechanism is based on System.Threading.ReaderWriterLock. This means that we can do many reads but only one writing at the same time. ASP.NET Session object is configured for full (read\write) access, by default. That's why we need to configure Session object as 'read-only' on long-term pages to have non-blocking access to Session object from other pages. Be aware that even you don't use Session object explicitly you have this issue too.

How to reproduce

To reproduce this issue let's create 2 asp.net pages.

Default page:

<%@ Page Language="C#" %>

<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
      Response.Write("Hello, SessionId " + Session.SessionID);
  }
</script>

Slow page (contains some long-term execution):

<%@ Page Language="C#" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(10000);
        Response.Write("Hello, SessionId " + Session.SessionID);
    }
</script>

web.config

<configuration>
  <system.web>
    <sessionState mode="InProc"/>
  </system.web>
</configuration>

To resolve this issue we can re-configure ASP.NET Session object access. Session state is configured by using the sessionState element of the system.web configuration section. If you need non-blocking access to read from Session:

<%@ Page Language="C#" EnableSessionState="ReadOnly"%>

If you don't need Session:

<%@ Page Language="C#" EnableSessionState="False"%>



ASP.NET European Hosting - HostForLIFE.eu :: ASP.NET Identity

clock February 21, 2014 08:51 by author Peter

ASP.NET Identity provides an implementation of user and and rolemanagement. ASP.NET Identity does not do authentication. Cookie based authentication and redirects to external login providers such as Google and Facebook is handeled by the OWIN libraries. ASP.NET Identity is only concerned with creation of users and roles, and persisting information about users such as passwords, links to external login providers and claims. This functionality is provided by classes in the two assemblies

1. Microsoft.AspNet.Identity.Core - Core user and role management logic

2. Microsoft.AspNet.Identity.EntityFramework - EnitityFramework based persistence of Users, Roles, Claims etc.

Identity Core - user management logic

Identity.Core has two main classes which will be our main means to interact with ASP.NET Identity. They are named UserManager and RoleManager. UserManager is probably the most important one, and is the only one that are used in the AccountController that is created by the default templates for e.g. an MVC when you choose "Individual User Accounts".

The UserManager is used to add/create, find/get and remove:

1. Users
2. Passwords
3. Claims
4. Link to roles
5. Link to logins

A UserStore that is responsible for the persistence is injected into the UserManager. The usermanager will use the UserStore to perform all it's needs for persistence. The UserManager is a generic class that has a TUser type parameter. TUser must be a class that implements the IUser interface, which means that a User class needs to have a Id getter of string type and a UserName string property.

Developers often asks why Microsoft chose to type the Id as string instead of int. It is true that if we implement our own UserStore then we are free to use a different type for our primary key, but it is a bit inconvenient that this key can not be named "Id". IUser which we must implement already defines a string Id get'er.

Identity EntityFramework - Entity framework code first persistence

The classes of the Identity Core assembly require a persistence mechanism. Microsoft has provided a Entity Framework code first based implementation to us in the assembly Microsoft.AspNet.Identity. The Identity EntityFramework assembly provides a UserStore implementation that can be plugged right into the UserManager from the Core assembly. This is by far our easiest option to get started with ASP.NET Identity. In fact if you create a new MVC project and choose Individual User Accounts the template will create a working implementation for you right away.

The model consist of a IdentityUser and the following related objects:

1. IdentityUserClaim. A list of claims for the user

2. IdentityUserLogin. This is only used for external logins. Links the local user to an external account

3. IdentityRole. If you use roles this is where the roles and mapping from user to roles will be stored.

Simplicity comes at a price

This simplicity comes at a price though. The UserStore require us to not only have our user class implement the IUser interface, it also demands that we need to inherit from the ASP.NET Identity EntityFramework class called IdentityUser which adds two new properties to the IUser interface. The hashed password and a SecurityStamp is stored on the user. Many developers and myself included are not too happy about being forced to have a reference to EntityFramework and ASP.NET EntityFramework from our domain model assembly and that we are required to inherit from this IdentityUser class, but if we want to have the simplicity of just using the Microsoft Identity persistence then we just have to swallow that one.

The UserStore will by default create a DbContext that in turn will create five tables for us, one for each of the entities in the model.

1. AspNetUsers - for storing IdentityUser

2. AspNetUserClaims - for storing IdentiyUserClaim

3. AspNetUserLogin - for storing IdentityUserLogin

4. AspNetRoles - for storing IdentityRole

5. AspNetUserRoles - for storing the many-to-many relation between IdentityUser and IdentityRole

The table names and the Entity Framework configuration of relations between the entities are configured in the OnModelCreating method of the IdentityDbContext that the UserStore will create if we don't provide our own DbContext. If we want to use different table names or map things differently in our database we need to provide our own DbContext. We can either create a completely new DbContext class with the 5 required DbSets (one for each of the model classes) or we can simply subclass the IdentityDbContext and override the OnModelCreating method where we can configure the EF mappings as we wish.

What next?

As I wrote in my previous post I was hoping that Microsoft would remove the requirement of having to inherit the IdentityUser. As we have seen, it didn't happen.

If we want to use the stock implementation in the form of ASP.NET Identity EntityFramework we have to inherit from the IdentityUser class. Still, what they did do was refactor the implementation into two clearly separate concerns. The core assembly containing the core logic and the EntityFramework assembly containing EF persistence. It's the latter that forces me to do things I don't like, and because the designers has made this clean separation it is possible for me to opt out of the EF persistence implementation while still use the user management logic in the Core assembly. In my next post I will show how to write my own UserStore class. To show that the ASP.NET Identity model is flexible and in no way tied to Entity Framework or SQL server I will be persisting my user data to a MongoDatabase instead of using Entity Framework.



ASP.NET 4.5.1 France Hosting - HostForLIFE.eu :: How to restrict size of file upload in ASP.NET

clock February 10, 2014 06:49 by author Peter

I have one page that contains one file upload control to accept files from user and saving it in one folder. I have written code to upload file and saving it to folder it’s working fine after completion of my application my friend has tested my application like he uploaded large size file nearly 10 MB file at that time it’s shown the error page like “the page cannot displayed”. This topic contains only brief information about ASP.NET, if you're loooking for ASP.NET Hosting and want to be more familiar with ASP.NET, you should try HostForLIFE.eu.

Again I have search in net I found that file upload control allows maximum file size is 4MB for that reason if we upload file size larger than 4MB we will get error page like “the page cannot displayed” or “Maximum request length exceeded”. After that I tried to increase the size of uploaded file by setting some properties in web.config file like this:

 <system.web> 
 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 
 </system.web> 

Here httpRuntime means: Configures ASP.NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

executionTimeout means: Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

maxRequestLength means: Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB).

After that write the following code in aspx page

 <html xmlns="http://www.w3.org/1999/xhtml"> 
 <head id="Head1" runat="server"> 
 <title>Untitled Page</title> 
 </head> 
 <body> 
 <form id="form1" runat="server"> 
 <div> 
 <asp:FileUpload ID="FileUpload1" runat="server" /> 
 <br /> 
 <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" /> 
 <br /> 
 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
 </div> 
 </form> 
 </body> 
 </html> 
 After that write the following code in code behind 
 protected void btnUpload_Click(object sender, EventArgs e) 
 { 
 if (FileUpload1.HasFile) 
 { 
 if (FileUpload1.PostedFile.ContentLength < 20728650) 
 { 
 try 
 { 
 Label1.Text = "File name: " + 
 FileUpload1.PostedFile.FileName + "<br>" + 
 FileUpload1.PostedFile.ContentLength + " kb<br>" + 
 "Content type: " + 
 FileUpload1.PostedFile.ContentType; 
 } 
 catch (Exception ex) 
 { 
 Label1.Text = "ERROR: " + ex.Message.ToString(); 
 }  
 } 
 else 
 { 
 Label1.Text = "File size exceeds maximum limit 20 MB."; 
 } 
 } 
 } 


After that write the following code in web.config

 <system.web> 
 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 
 </system.web>



ASP.NET France Hosting - HostForLIFE.eu :: How to consume an XML feed in ASP.NET – RSS

clock February 5, 2014 15:41 by author Peter

In this example i am showing how to use Cross Page Posting or Postback In ASP.NET 2.0, 3.5, 4.0 Using C#. Cross Page posting is used to submit a form on one page (say default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx). There are two ways we can use cross page postsbacks in ASP.NET.

1st method
In this i've created a Default.aspx page with two textbox and one button , button click will post back to Default2.aspx and there we will retrieve and show values of both textboxes Html source of Default.aspx page is like

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox><br /><br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br /><br /><br />
       
<asp:Button ID="btnSubmit" runat="server"
            OnClick="btnSubmit_Click"
            PostBackUrl="~/Default2.aspx"
            Text="Submit to Second Page" /><br />
</div>
</form>
</body>
</html>

Don't forget to set PostBackUrl Property of Button
PostBackUrl="~/Default2.aspx"

Now to retrieve values of textBoxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx)

protected void Page_Load(object sender, EventArgs e)

{
    //Check whether previous page is cross page post back or not
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        TextBox txtPbFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
        TextBox txtPbLastName = (TextBox)PreviousPage.FindControl("txtLastName");
        Label1.Text = "Welcome " + txtPbFirstName.Text + " " + txtPbLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}

If you are using masterpages then you need to write code to FindControl as mentioned below

ContentPlaceHolder exampleHolder =(ContentPlaceHolder)Page.PreviousPage.Form.FindControl ("Content1"));
TextBox txtExample = exampleHolder.FindControl("txtFirstName");

2nd Method
Using Property to expose and Consume values of TextBox
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Html of the page needs no changes ,
C# code behind for Default.aspx
public TextBox pbTxtFirstName
    {
        get
        {
            return txtFirstName;
        }
    }
 
    public TextBox pbTxtLastName
    {
        get
        {
            return txtLastName;
        }
    }

Now write this code in page_Load event of second page to retrieve values of controls

protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        Label1.Text = "Welcome " + PreviousPage.pbTxtFirstName.Text + " " + PreviousPage.pbTxtLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}



ASP.NET 4 European Hosting - HostForLIFE.eu :: Tips to Improve ASP.NET Application Performance

clock February 4, 2014 06:35 by author Peter

Web application is designed to handle hundreds and thousands of requests per seconds so to handle these requests effectively and successfully it is important to resolve any potential performance bottlenecks. Now we will state some tips that improve the performance of your web application. Try HostForLife.eu, only with € 3.00/month, you can get a reasonable price with best service. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try HostForLife.eu.

1. Cache Commonly used objects
You can cache commonly used objects in ASP.Net using Cache class that provides an extensive caching mechanism that storing resources and allow you to:

- Define an expiration for a cached object either by specified a TimeSpan or a fixed DateTime.

- Define priority for cached objects. when there is a memory lack and objects need to be freed.

- Define validity for a cached object by adding dependacies

- Attach callbacks to cached objects,so when an objects is removed from cache the callback is invoked.

you can add objects to cache by adding it to cache Dictionary.

Cache["Mykey"] = myObject;

or using Insert method of Cache class

Cache.Insert("MyKey",myObject, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(60), dependacies : null );

2. Using Asynchronous Pages,Modules and Controllers
When IIS passes a request to ASP.NET, the request is queued to the thread pool and a worker thread is assigned to handle this request. the worker thread is limited so any new request will be queued to be handle after the current requests handled. If a request need to do some I/O operation like retrieving data from  a database or calling web service that mean you need to reduce the request time.

You can change I/O operation in your web page by making it as Asynchronous Page. In ASP.NET you can do that by firstly marking the page as async

<%@ Page Async="true"....

then create new PageAsyncTask object and pass it the delegates for the begin, end, and timeout methods. After creating PageAsyncTask object, call the Page.RegisterAsuncTask method to start the asynchronous opertaion.

public partial class MyAsyncPage : System.Web.UI.Page
{
   private SqlConnection _sqlConnection;
   private SqlCommand _sqlCommand;
   private SqlDataReader _sqlReader;

   IAsyncResult BeginAsyncOp(Object sender, EventArgs e, AsyncCallback cb, Object state)
   {
       // this method will be executed in the original worker thread,
       //so don't do any lengthy operation here
       _sqlcommand = CreateSqlCommand(_sqlConnection);
       return _sqlCommand.BeginExecuteReader();
   }
   void EndAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   void TimeoutAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   public override void Dispose()
   {
       if(_sqlConnection != null)
       {
           _sqlConnection.Close();
       }
   }
   protected void btnClick_Click(Object sender, EventArgs e)
   {
       PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginAsyncOp),
                                               new EndEventHandler(EndAsyncOp),
                                               new TimeoutEventHandler(TimeoutAsyncOp),
                                               state : null);
       RegisterAsyncTask(task);
   }
}

There is another way to create async pages is by using completion events.

public partial class MyAsyncPage2 : System.Web.UI.Page
{
   protected void btnGetData_Click(Object sender , EventArgs e)
   {
       Services.MyService serviceProxy = new Services.MyService();
       serviceProxy.GetDataCompleted +=Services.GetDataCompletedEventHandler(GetData_Completed);
       serviceProxy.GetDataAsync();
   }
   void GetData_Completed(Object sender,Services.GetDataCompletedEventArgs e)
   {
       //Extract the result from the event args and build the page's content
   }

}

In ASP.NET MVC you can create such mechanisme by creating Asynchronous Controller. To create such contoller you need to follow these four steps:

- Create a Controller class that inherits from the AsyncController type.

- Implement  a set of action methods for each async operation according to the following convention, where xx is the name of the action: xxAsync and xxCompleted.

- In the xxAsync method, call the AsyncManager.OutstandingOperations.Increment method with the number of asynchronous operations you are about to perform.

- In the code which executes during the return of the async operation, call the AsyncManager.OutstandingOperations.Decrement method to notify the operation has completed.

The following code shows you how to implement these steps:

public class MyController : AsyncController
{
   public void IndexAsync()
   {
       AsyncManager.OutStandingOperations.Increment();      
       MyService serviceProxy = new MyService();
       serviceProxy.GetDataCompleted += (sender , e) => {
                                        AsyncManager.Parameters["result"] = e.Value;
                                        AsyncManager.OutStandingOperations.Decrement();
                                        };
       serviceProxy.GetHeadlinesAsync();
   }
   public ActionResult IndexCompleted(MyData result)
   {
       return view("Index",new MyViewModel { TheData = result });
   }
}

3. Turn off ASP.NET Tracing and debugging
before deploying your web application turn of tracing feature by setting it to false in web.config file

<configuration>
    <system.web>
        <trace enabled="false" />
    </system.web>
</configuration>

While development phase you need to enable debugger to debug your code by setting it to true in web.config file. Neglecting change it again to false before deploying will affect your web application performance by facing many problems:

- Scripts that are downloaded using the WebResources.axd handler, by setting debug to false responses from that handler will be returned with caching headers, allowing browsers to cache the responses for future use.

- Request will not timeout when debug is set to true. By setting it to false will enable ASP.NET to define timeouts for requests according to the HttpRuntime.Execution Timeout configuration settings.

- JIT optimization will not be applied to the code when running with debug = true. JIT can efficiently improve the performance of your ASP.NET application without requiring you change your code.

- The compilation process does not use batch compilation when using debug = true. without batch compilation an assembly will be created for each page and control causing web application to load so many of assemblies during runtime. When debug set to false batch compilation is used, generating a single assembly for the user control and a several assemblies for pages.

in case you fear to forget setting debug to false when deploying your application, you can force all ASP.NET applications in a server to ignore the debug setting by adding  the following configurations in the server's machine.config file.

<configuration>
    <system.web>
        <deployment retail="true" />
    </system.web>
</configuration>

4. Disable View State
View state is used to allow ASP.NET to keep the state of the page between postbacks performed by user. View state data is stored in HTML output inside hidden field. If your page displays many controls that contains a huge data, the view state field will be big enough to affect the response time of your page. if your page just display data without need any postback so it will be better to disable the view state of the whole page by set EnableViewState to false.

<%@ Page EnableViewState="false".......%>

or disable view state of some controls in your page

<Asp:GridView ID="MyGrid" runat="server" DataSource="MyDataSource" EnableViewState="false" />

if you don't want to use view state in all pages of your web application it recommended to disable view state for whole web application by setting it to false in your web.config file

<system.web>
    <pages enableViewState="false" ....../>
</system.web>

5. Pre-Compiling ASP.NET Application
When compiling an ASP.NET application project, a single assembly is created to hold all application's code but web pages(.aspx) and user controls(.ascx) not compiled and be deployed as it is. In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder.
To reduce the time of first request the web application can be pre-compiled, including all code, pages, and user controls, by using the ASP.NET compilation tool (Aspnet_compiler.exe). Running this tool in production servers can reduce the delay users experience on first requests.

- Open a command prompt in your production server.

- Navigate to the %windir%\Microsoft.Net folder

- Navigate to either the Framework or Framework64 according to the configuration of web application's application pool.

- Navigate to framework version's folder.

- Enter the following command to start the compilation

Aspnet_compiler.exe  -v  /FullPathOfYourWebApplication



European Italy HostForLIFE.eu Proudly Launches ASP.NET 4.5.1 Hosting

clock January 30, 2014 06:07 by author Scott

HostForLIFE.eu proudly launches the support of ASP.NET 4.5.1 on all their newest Windows Server environment. HostForLIFE.eu ASP.NET 4.5.1 Hosting plan starts from just as low as €3.00/month only.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 4.5.1 with lots of awesome features.

According to Microsoft officials, much of the functionality in the ASP.NET 4.5.1 release is focused on improving debugging and general diagnostics. The update also builds on top of .NET 4.5 and includes new features such as async-aware debugging, ADO.NET idle connection resiliency, ASP.NET app suspension, and allows developers to enable Edit and Continue for 64-bit.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

The new ASP.NET 4.5.1 also add support for asynchronous debugging for C#, VB, JavaScript and C++ developers. ASP.NET 4.5.1 also adds performance improvements for apps running on multicore machines. And more C++ standards support, including features like delegating constructors, raw string literals, explicit conversion operators and variadic templates.

Microsoft also is continuing to add features meant to entice more JavaScript and HTML development for those using Visual Studio to build Windows Store. Further information and the full range of features ASP.NET 4.5.1 Hosting can be viewed here http://www.hostforlife.eu/European-ASPNET-451-Hosting.



European ASP.NET Hosting - Nederland :: How to Solve System.Net.Mail: The specified string is not in the form required for a subject

clock January 21, 2014 08:59 by author Scott

Sometimes you’ll see this error on your site and it is really annoying. I post this issue as I see many people on forums experiencing on this issue. This is an error message:

“ArgumentException: The specified string is not in the form required for a subject“.

So what is exactly “the form required for a subject”? Googling for this error message returns a lot of junk and misinformed forum posts. It turns out that setting the Subject on a System.Net.Mail.Message internally calls MailBnfHelper.HasCROrLF (thank you Reflector) which does exactly what it says on the tin. Therefore one forum poster’s solution of subject.Replace("\r\n", " ") isn’t going to work when you have either a carriage returnor line feed in there.

The solution is like this:

message.Subject = subject.Replace('\r', ' ').Replace('\n', ' ');

Personally, I think that the MailMessage should to this for you or at least Microsoft should document what actually constitutes a “form required for a subject” in MSDN or, even better, in the actual error message itself!

 



European ASP.NET 4.5 Hosting - Amsterdam :: Model Binding with Dropdown List in ASP.NET 4.5

clock December 20, 2013 05:32 by author Administrator

ASP.NET 4.5 Preview introduces new model binding for  ASP.NET web forms. The concept of model binding was first introduced with ASP.NET MVC and now it has incorporated with ASP.NET Web Forms. You can easily perform any CURD operation with any sort of data controls using any data access technology like Entity Framework,  ADO.NET, LINQ to SQL Etc.  In this post I am going talk about how you can bind the data with ASP.NET DropdownList using new Model Binding features.

Let’s say we have a speaker database and we wants to bind the name of the speakers with the DropDownList.  First placed an ASP.NET Dropdown control with the page  and set the “DataTextField” and “DataValueField” properties.

We can set the  ddlName.DataSource to specifying the data source from the code behind and bind the data with dropdpwnlist, but  in this case from the code behind to providing the data source.

Now, instead of specifying the DataSource, we will be setting the Dropdownlists SelectMethod property to point a method GetSpeakerNames() within the code-behind file.

Select method is expected to return us result of type IQueryable<TYPE>. Here is GetSpeakerName() method is defined as follows.

So, Instead of specifying the data source we are specifying the SelectMethod, which return the IQueryable type of Speaker object. Run the application, you will find the names binded with dropdown list. Hope this helps !



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in