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 Hosting - Belgium - HostForLIFE.eu :: Basic Authentication with ASP.NET Web API Using Authentication Filter

clock March 10, 2014 07:42 by author Peter

Authorization filters and action filters have been around for a while in ASP.NET Web API but there is this new authentication filter introduced in Web API 2. Authentication filters have their own place in the ASP.NET Web API pipeline like other filters. Historically, authorization filters have been used to implement authentication and there is ton of samples out there with all kinds of authentication implemented in authorization filters. Web API 2 introduces the authentication filter so that authentication concerns can be separated out of authorization filter and put into an authentication filter.

This blog post is just a quick introduction to writing a custom authentication filter for implementing HTTP Basic Authentication. There is a full-blown example here, if you are interested in writing a production-strength filter.First up, we create the filter class BasicAuthenticator implementing the IAuthenticationFilter interface. We also derive from Attribute so that we can apply the filter on action methods, like so.

public class EmployeesController : ApiController
{
    [BasicAuthenticator(realm: "Magical")]
    public HttpResponseMessage Get(int id)
    {
        return Request.CreateResponse<Employee>(
        new Employee()
        {
            Id = id,
            FirstName = "Johnny",
            LastName = "Law"
        });
    }
}

There are two interesting methods that we need to implement in the filter – (1) AuthenticateAsync and (2) ChallengeAsync.

AuthenticateAsync contains the core authentication logic. If authentication is successful, context.Prinicipal is set. Otherwise, context.ErrorResult is set to UnauthorizedResult, which basically gets translated to a “401 – Unauthorized” HTTP response status code.

public class BasicAuthenticator : Attribute, IAuthenticationFilter
{
    private readonly string realm;
    public bool AllowMultiple { get { return false; } }
 
    public BasicAuthenticator(string realm)
    {
        this.realm = "realm=" + realm;
    }
 
    public Task AuthenticateAsync(HttpAuthenticationContext context,
                                  CancellationToken cancellationToken)
    {
        var req = context.Request;
        if (req.Headers.Authorization != null &&
                req.Headers.Authorization.Scheme.Equals(
                          "basic", StringComparison.OrdinalIgnoreCase))
        {
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string credentials = encoding.GetString(
                                  Convert.FromBase64String(
                                      req.Headers.Authorization
                                                   .Parameter));
            string[] parts = credentials.Split(':');
            string userId = parts[0].Trim();
            string password = parts[1].Trim();
 
            if (userId.Equals(password)) // Just a dumb check
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, "badri")
                };
                var id = new ClaimsIdentity(claims, "Basic");
                var principal = new ClaimsPrincipal(new[] { id });
                context.Principal = principal;
            }
        }
        else
        {
            context.ErrorResult = new UnauthorizedResult(
                     new AuthenticationHeaderValue[0],
                                          context.Request);
        }
 
        return Task.FromResult(0);
    }
 
    public Task ChallengeAsync(
                     HttpAuthenticationChallengeContext context,
                            CancellationToken cancellationToken) {}
}

For basic authentication, when there is a 401, we are supposed to send WWW-Authenticate header and the right place to write such challenge related logic will be the ChallengeAsync method. This is where things get interesting because it is not so straight forward to add headers here. The recommended approach is to create a class implementing IHttpActionResult and set an instance of it to context.Result, like so.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                                      CancellationToken cancellationToken)
{
    context.Result = new ResultWithChallenge(context.Result, realm);
    return Task.FromResult(0);
}

Here is the result class. The crux of this class is in the ExecuteAsync method and that is where we set the WWW-Authenticate response header indicating the scheme and the realm.

public class ResultWithChallenge : IHttpActionResult
{
    private readonly IHttpActionResult next;
    private readonly string realm;
 
    public ResultWithChallenge(IHttpActionResult next, string realm)
    {
        this.next = next;
        this.realm = realm;
    }
 
    public async Task<HttpResponseMessage> ExecuteAsync(
                                CancellationToken cancellationToken)
    {
        var res = await next.ExecuteAsync(cancellationToken);
        if (res.StatusCode == HttpStatusCode.Unauthorized)
        {
            res.Headers.WwwAuthenticate.Add(
               new AuthenticationHeaderValue("Basic", this.realm));
        }
 
        return res;
    }
}

For setting the WWW-Authenticate response header, we created a class. However, it is possible to get away without creating one, like this.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                               CancellationToken cancellationToken)
{
    var result = await context.Result.ExecuteAsync(cancellationToken);
    if (result.StatusCode == HttpStatusCode.Unauthorized)
    {
        result.Headers.WwwAuthenticate.Add(
                new AuthenticationHeaderValue(
                    "Basic", "realm=" + this.realm));
    }
    context.Result = new ResponseMessageResult(result);
}

However, this approach will not work with MVC since there is no ResponseMessageResult. For the sake of consistency, it is better to create our own class. Also, the code above changes the pipeline behavior slightly. For these reasons, it is recommended to create a class implementing IAuthenticationFilter (the initial approach in this post).



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



Press Release - Wordpress 3.8 Hosting with HostForLIFE.eu from Only €3.00/month

clock January 23, 2014 10:40 by author Scott

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

WordPress is a flexible platform which helps to create your new websites with the CMS (content management system). There are lots of benefits in using the WordPress blogging platform like quick installation, self updating, open source platform, lots of plug-ins on the database and more options for website themes and the latest version is 3.8 with lots of awesome features.

WordPress 3.8 was released in December 2013, which introduces a brand new, completely updated admin design: with a fresh, uncluttered aesthetic that embraces clarity and simplicity; new typography (Open Sans) that’s optimized for both desktop and mobile viewing; and superior contrast that makes the whole dashboard better looking and easier to navigate.

HostForLIFE.eu is a popular online WordPress 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.

Another wonderful feature of WordPress 3.8 is that it uses vector-based icons in the admin dashboard. This eliminates the need for pixel-based icons. With vector-based icons, the admin dashboard loads faster and the icons look sharper. No matter what device you use – whether it’s a smartphone, tablet, or a laptop computer, the icons actually scale to fit your screen.

WordPress 3.8 is a great platform to build your web presence with. HostForLIFE.eu can help customize any web software that company wishes to utilize. Further information and the full range of features WordPress 3.8 Hosting can be viewed here http://www.hostforlife.eu.

 



European ASP.NET 4.5 Hosting - HostForLIFE.eu :: Send Bulk Email Using ASP.NET 4.5

clock January 22, 2014 05:58 by author Scott

This article explains how to send bulk email using ASP.Net 4.5. You can use:

  • ASP .NET web page
  • Grid View
  • HTML Email Templates
  • Gmail SMTP Mail Server

Create a new project using "File" -> "New" -> "Project..." then select web "ASP .Net Web Forms Application". Name it " Bulk Email".

Now in the Design page “Default.aspx” design the web page as in the following screen:

In the Design Source (Default.aspx) write the code as: 

Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
 Inherits="BulkEmail._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
   
 <section class="featured">
       
 <div class="content-wrapper">
           
 <hgroup class="title">              
               
 <h2>Send Bulk email using asp.net</h2>
           
 </hgroup>
           
 <p>
                To learn more about ASP.NET
           
 </p>
       
 </div>
   
 </section>
</asp:Content>
<asp:Content
 runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
      
 <h3>We suggest the following:</h3>
   
 <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
   
 <p>
      
 <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1"
 runat="server" Font-Bold="true" ForeColor="Green" Text="Total Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size
="Larger"></asp:Label> </p>
   
 
       
 <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
       
 <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>

   
 </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:

Web.config

<connectionStrings>     
   
<add
 name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      

</connectionStrings>

In the code behind file (Default.aspx.cs) write the code as: 

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

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
   
 
public partial class _Default : Page
    {
        #region MySqlConnection Connection
       
 
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

       
 protected void Page_Load(object sender, EventArgs e)
        {
           
 
Try
            {
               
 if (!Page.IsPostBack)
                {

                }
            }
           
 
catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
       
 
/// <summary>
       
 /// This function is used for show message.
       
 /// </summary>
       
 /// <param name="msg"></param>
       
 void ShowMessage(string msg)
        {
           
 ClientScript.RegisterStartupScript(Page.GetType(), 
"validation", "<script
language='javascript'>alert('"
 + msg + "');</script>");
        }      
 
        #endregion
        #region Bind Data
       
 
/// <summary>
       
 /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter

       
 /// </summary>
       
 /// <param name="sender"></param>
       
 /// <param name="e"></param>
       
 protected void btnBind_Click(object sender, EventArgs e)
        {
           
 
Try
            {
                conn.Open();
               
 MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers"
, conn);
               
 MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
               
 DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
           
 catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
           
 
Finally
            {
                conn.Close();

            }
            btnBind.Visible =
 false;
        }
        #endregion
        #region Bulk email,GridView,gmail
       
 
/// <summary>
       
 /// this code used to Send Bulk email 
       
 /// </summary>
       
 /// <param name="sender"></param>
        
/// <param name="e"></param>
       
 protected void btnSend_Click(object sender, EventArgs e)
        {
           
 
Try
            {
                lbltotalcount.Text =
 string.Empty;
               
 foreach (GridViewRow grow in grvCustomers.Rows)
               {
                   
 
string strCustomerID = grow.Cells[0].Text.Trim();
                   
 
string strContactName = grow.Cells[1].Text.Trim();
                   
 
string strAddress = grow.Cells[2].Text.Trim();
                   
 
string strPhone = grow.Cells[3].Text.Trim();
                   
 
string strEmail = grow.Cells[4].Text.Trim();                

                   
 
string filename = Server.MapPath("~/Event.html");
                   
 string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace(
"##NAME##", strContactName);
                   
 string to = strEmail;
                   
 
string from = "[email protected]";
                   
 MailMessage message = new MailMessage(from, to);
                    message.Subject =
 "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding =
 Encoding.UTF8;
                    message.IsBodyHtml =
 true;
                   
 SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.
NetworkCredential basicCredential = new
System.Net.
NetworkCredential("[email protected]", "Password");
                    client.EnableSsl =
 true;
                   
 client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                   
 try
                    {
                        client.Send(message);
                        ShowMessage(
"Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                   
 catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
           
 
catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
           
 
Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}

See the following screen for the Default.aspx: Total Customers data bind.

Now, see the following screen for the Default.aspx: send email waiting.

Now, show in the Message box “Email sending successfully”.

Now "Email Account Open" - > "View Email". You’ll see the messages on your inbox. Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server. I hope this article is useful. 



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!

 



Press Release - European Germany HostForLIFE.eu Proudly Launches Umbraco 7 Hosting

clock January 15, 2014 11:35 by author Scott

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the supports for Umbraco 7 Hosting plan due to high demand of Umbraco 7 CMS users in Europe. Umbraco 7 features the stable engine of Umbraco 6 powering hundreds of thousands of websites, but now enriched with a completely new, remarkably fast and simple user interface.

Umbraco is fast becoming the leading .NET based, license-free (open-source) content management system. It is an enterprise level CMS with a fantastic user-interface and an incredibly flexible framework which is both scalable and easy to use. Umbraco is used on more than 85,000 websites, including sites for large companies such as Microsoft and Toyota.

HostForLIFE.eu is a popular online Umbraco 7 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.

Umbraco has given a lot of thought to the user experience of their CMS. The interface uses a navigational flow and editing tools that anybody using Windows Explorer and Microsoft Word will immediately recognise. Your site structure sits in a tree view - just like Windows Explorer. Anybody with experience using Microsoft Word, can use Umbraco's simple rich text editing (RTE) interface.

"Umbraco 7 is easy to install within few clicks, special thanks to HostForLIFE.eu special designed user friendly web hosting control panel systems." - Ivan Carlos, one of the many HostForLIFE.eu satisfying clients.

Further information and the full range of features Umbraco 7 Hosting can be viewed here http://hostforlife.eu/European-Umbraco-7-Hosting.



Press Release - European HostForLIFE.eu Proudly Launches DotNetNuke 7.1 Hosting

clock January 7, 2014 07:19 by author Scott

HostForLIFE.eu proudly launches the support of DotNetNuke 7.1 on all our newest Windows Server 2012 environment. Our European DotNetNuke 7.1 Hosting plan starts from just as low as €3.00/month only and this plan has supported ASP.NET 4.5, ASP.NET MVC 4 and SQL Server 2012.

DotNetNuke (DNN) has evolved to become one of the most recognizable open source Content Management systems. Basically it is based on the Microsoft platform, i.e. ASP.NET, C#, SQL, jQuery etc. As a web development platform, DotNetNuke provides a solid base platform.

HostForLIFE.eu clients are specialized in providing supports for DotNetNuke CMS for many years. We are glad to provide support for European DotNetNuke CMS hosting users with advices and troubleshooting for our clients website when necessary.

DNN 7.1 provides intuitive drag-n-drop design feature, streamlined interface, built in social authentication providers, fully integrated SEO (Search Engine Optimization), membership system, granular access control, and many other features. In fact DNN 7 is all in one web development and content management system. No longer is the site design realm of just technically inclined, DNN 7 delivers advanced features and capabilities that are not matched by other CMS systems. In fact it is most well rounded CMS system available to date.

DotNetNuke 7.1 is a great platform to build your web presence with. HostForLIFE.eu can help customize any web software that company wishes to utilize. Further information and the full range of features DotNetNuke 7.1 Hosting can be viewed here http://hostforlife.eu/European-DotNetNuke-71-Hosting.

 



European ASP.NET 4.5 Hosting - Amsterdam :: New Feature Multicore JIT in .NET Framework 4.5

clock December 30, 2013 07:45 by author Scott

This articles describe one of the newest runtime features in ASP.NET 4.5. I will describe about Muticore Just-In-Compiler (JIT) in the .NET framework 4.5.

Multicore Just-in-Time (JIT) 

In the .NET framework 4.5, Microsoft has introduced an enhancement of the pervious JIT compiler by making it a Multicore JIT compiler, that runs on the two cores and supports parallelism in the compilation process in order to improve the launch performance during application startup.

From the developer point of view the Multicore JIT is a very cool runtime feature in .NET Framework 4.5 to improve their productivity and speed up the overall performance of an application. Now the developer can benefit from multicore processors to speed up the application compilation process.

The Multicore JIT compiler works in parallel with two cores. Because of the two cores, Multicore JIT can make your application start the process faster at startup. Multicore JIT provides significant improvements to Web based applications as well as Desktop Windows Presentation Foundation (WPF) applications.

Working of Multicore JIT

Nowadays, every PC has at least two cores, so the JIT compiler is built to make the investment worthwhile. Using the Multicore JIT, methods are compiled on two CPUs so that the application is able to reach the end of its startup execution quickly.

The compilation process is done in two cores that run in parallel executing the Multicore JIT compiler. The more effective Multicore JIT will reduce the startup time of an .NET application. 

Multicore JIT uses the two modes of operation.

Recording mode: It is the first mode, when JIT compiles the entire program and creates a JIT profile using a profile optimization class and saves the profile that was executed to a given folder to disk.

Playback mode: This mode is used when the application is launched subsequently. Playback mode is used to load the profile that was saved during the Recording mode from the disk using the background JIT thread in order to support the main thread.

The feature works by the JIT compiling the methods likely to be executed based on profiles created during previous compilations, that will runs on a separate processor core taking care of the JIT Compilation while the main execution thread runs on a different core.

In the ideal case, the second core quickly gets ahead of the mainline execution of the application, so whenever a method is required it is already compiled. As a result, the main thread doesn't need to do as much compilation, and your application launches faster.

In order to know which methods to compile, the feature generates profile data in the Recording mode that keeps track of the methods that are executed. Then the next time the application runs the call will look for that profile and when it finds it then it plays back; that means it starts compiling all the methods that was saved for that profile.

Note: MultiCore JIT requires a multicore machine to take advantage of its algorithms otherwise the CLR will ignore it on single core machines.

How to enable Multicore JIT in an .NET 4.5 application.

You can use this feature of the runtime to significantly improve the startup times of both client applications and Web sites in .NET framework 4.5.

Since ASP.NET applications run in a hosted environment, this feature is turned on for these applications automatically. Therefore JIT compiling using multiple cores is enabled by default in ASP.NET 4.5 and Silverlight 5.

But, if you want to disable this feature in your ASP.NET 4.5 applications then write the following code in the web.config file.

<system.web>
  <compilation profileGuidedOptimizations="None" />
</system.web>

But in a Windows based application, you will need to enable Multicore JIT feature explicitly.

Let's see how.

It is simple to use Multicore JIT, there is a class in the .NET Framework named "System.Runtime.ProfileOptimization" that you can use to start profiling at the entry point of your application. 

Optimization Profilers

The ProfileOptimization is a new type introduced in .Net 4.5 to improve the startup performance of application domains in applications that require the just-in-time (JIT) compiler by performing background compilation of methods that are likely to be executed, based on profiles created during previous compilations.

See the MSDN documentation for more information.

http://msdn.microsoft.com/en-IN/library/system.runtime.profileoptimization.aspx

The two methods that you can call at the entry point of your application.

SetProfileRoot: This method is used to specify the root path, where to save the JIT profile compiled information for optimization.

StartProfile: This method is used to start Multcore just in-time compilation.

You must write the following code in your application constructor in order to enable Multicore JIT.

public App()
{

 ProfileOptimization.SetProfileRoot(@"C:\MyAppFolder");
 ProfileOptimization.StartProfile("Startup.Profile");

}

Now that's all to enable the Multicore feature in your application; the rest of the work will be handled by the CLR automatically.



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 !



European ASP.NET 4.5 Hosting - Amsterdam :: Tutorial Customize ASP.NET 4.5 Membership

clock December 17, 2013 10:29 by author Patrick

The ASP.NET MVC 4 Internet template adds some new, very useful features which are built on top of SimpleMembership. These changes add some great features, like a much simpler and extensible membership API and support for OAuth. However, the new account management features require SimpleMembership and won't work against existing ASP.NET Membership Providers. I'll start with a summary of top things you need to know, then dig into a lot more detail.

Summary:

  • SimpleMembership has been designed as a replacement for the previous ASP.NET Role and Membership provider system
  • SimpleMembership solves common problems developers ran into with the Membership provider system and was designed for modern user / membership / storage need
  • SimpleMembership integrates with the previous membership system, but you can't use a MembershipProvider with SimpleMembership
  • The new ASP.NET MVC 4 Internet application template AccountController requires SimpleMembership and is not compatible with previous MembershipProviders
  • You can continue to use existing ASP.NET Role and Membership providers in ASP.NET 4.5 and ASP.NET MVC 4 - just not with the ASP.NET MVC 4 AccountController
  • The existing ASP.NET Role and Membership provider system remains supported, as it is part of the ASP.NET core
  • ASP.NET 4.5 Web Forms does not use SimpleMembership; it implements OAuth on top of ASP.NET Membership
  • The ASP.NET Web Site Administration Tool (WSAT) is not compatible with SimpleMembership

The following is the result of a few conversations with Erik Porter (PM for ASP.NET MVC) to make sure I had some the overall details straight, combined with a lot of time digging around in ILSpy and Visual Studio's assembly browsing tools.

SimpleMembership: The future of membership for ASP.NET
The ASP.NET Membership system was introduced with ASP.NET 2.0 back in 2005. It was designed to solve common site membership requirements at the time, which generally involved username / password based registration and profile storage in SQL Server. It was designed with a few extensibility mechanisms - notably a provider system (which allowed you override some specifics like backing storage) and the ability to store additional profile information (although the additional  profile information was packed into a single column which usually required access through the API). While it's sometimes frustrating to work with, it's held up for seven years - probably since it handles the main use case (username / password based membership in a SQL Server database) smoothly and can be adapted to most other needs (again, often frustrating, but it can work).

The ASP.NET Web Pages and WebMatrix efforts allowed the team an opportunity to take a new look at a lot of things - e.g. the Razor syntax started with ASP.NET Web Pages, not ASP.NET MVC. The ASP.NET Web Pages team designed SimpleMembership to (wait for it) simplify the task of dealing with membership. As Matthew Osborn said in his post Using SimpleMembership With ASP.NET WebPages:
With the introduction of ASP.NET WebPages and the WebMatrix stack our team has really be focusing on making things simpler for the developer. Based on a lot of customer feedback one of the areas that we wanted to improve was the built in security in ASP.NET. So with this release we took that time to create a new built in (and default for ASP.NET WebPages) security provider. I say provider because the new stuff is still built on the existing ASP.NET framework. So what do we call this new hotness that we have created? Well, none other than SimpleMembership. SimpleMembership is an umbrella term for both SimpleMembership and SimpleRoles.

Part of simplifying membership involved fixing some common problems with ASP.NET Membership.

Problems with ASP.NET Membership
ASP.NET Membership was very obviously designed around a set of assumptions:

  • Users and user information would most likely be stored in a full SQL Server database or in Active Directory
  • User and profile information would be optimized around a set of common attributes (UserName, Password, IsApproved, CreationDate, Comment, Role membership...) and other user profile information would be accessed through a profile provider

Some problems fall out of these assumptions.
Requires Full SQL Server for default case
The default, and most fully featured providers ASP.NET Membership providers (SQL Membership Provider, SQL Role Provider, SQL Profile Provider) require full SQL Server. They depend on stored procedure support, and they rely on SQL Server cache dependencies, they depend on agents for clean up and maintenance. So the main SQL Server based providers don't work well on SQL Server CE, won't work out of the box on SQL Azure, etc.

Custom Membership Providers have to work with a SQL-Server-centric API
If you want to work with another database or other membership storage system, you need to to inherit from the provider base classes and override a bunch of methods which are tightly focused on storing a MembershipUser in a relational database. It can be done (and you can often find pretty good ones that have already been written), but it's a good amount of work and often leaves you with ugly code that has a bunch of System.NotImplementedException fun since there are a lot of methods that just don't apply.

Designed around a specific view of users, roles and profilesThe existing providers are focused on traditional membership - a user has a username and a password, some specific roles on the site (e.g. administrator, premium user), and may have some additional "nice to have" optional information that can be accessed via an API in your application.
This doesn't fit well with some modern usage patterns:

  • In OAuth and OpenID, the user doesn't have a password
  • Often these kinds of scenarios map better to user claims or rights instead of monolithic user roles
  • For many sites, profile or other non-traditional information is very important and needs to come from somewhere other than an API call that maps to a database blob

What would work a lot better here is a system in which you were able to define your users, rights, and other attributes however you wanted and the membership system worked with your model - not the other way around.

Requires specific schema, overflow in blob columns


Update: This schema has been improved a lot with Universal Providers. The views and stored procedures have been removed, and the tables are simplified.

SimpleMembership as a better membership system
As you might have guessed, SimpleMembership was designed to address the above problems.

Then we point SimpleMemberhip at that table with a one-liner:
WebSecurity.InitializeDatabaseFile("SecurityDemo.sdf", "Users", "UserID", "Username", true);

Broaden database support to the whole SQL Server family
While SimpleMembership is not database agnostic, it works across the SQL Server family. It continues to support full SQL Server, but it also works with SQL Azure, SQL Server CE, SQL Server Express, and LocalDB. Everything's implemented as SQL calls rather than requiring stored procedures, views, agents, and change notifications.

Note that SimpleMembership still requires some flavor of SQL Server - it won't work with MySQL, NoSQL databases, etc. You can take a look at the code in WebMatrix.WebData.dll using a tool like ILSpy if you'd like to see why - there are places where SQL Server specific SQL statements are being executed, especially when creating and initializing tables. It seems like you might be able to work with another database if you created the tables separately, but I haven't tried it and it's not supported at this point.

Easy to with Entity Framework Code First
The problem with with ASP.NET Membership's system for storing additional account information is that it's the gate keeper. That means you're stuck with its schema and accessing profile information through its API.

SimpleMembership flips that around by allowing you to use any table as a user store. That means you're in control of the user profile information, and you can access it however you'd like - it's just data. Let's look at a practical based on the AccountModel.cs class in an ASP.NET MVC 4 Internet project. Here I'm adding a Birthday property to the UserProfile class.

How SimpleMembership integrates with ASP.NET MembershipOkay, enough sales pitch (and hopefully background) on why things have changed. How does this affect you? Let's start with a diagram to show the relationship (note: I've simplified by removing a few classes to show the important relationships):
So SimpleMembershipProvider is an implementaiton of an ExtendedMembershipProvider, which inherits from MembershipProvider and adds some other account / OAuth related things. Here's what ExtendedMembershipProvider adds to MembershipProvider:

Membership in the ASP.NET 4.5 project template
ASP.NET 4.5 Web Forms took a different approach which builds off ASP.NET Membership. Instead of using the WebMatrix security assemblies, Web Forms uses Microsoft.AspNet.Membership.OpenAuth assembly. I'm no expert on this, but from a bit of time in ILSpy and Visual Studio's (very pretty) dependency graphs, this uses a Membership Adapter to save OAuth data into an EF managed database while still running on top of ASP.NET Membership.

How does this fit in with Universal Providers (System.Web.Providers)?
Just to summarize:

  • Universal Providers are intended for cases where you have an existing ASP.NET Membership Provider and you want to use it with another SQL Server database backend (other than SQL Server). It doesn't require agents to handle expired session cleanup and other background tasks, it piggybacks these tasks on other calls.
  • Universal Providers are not really, strictly speaking, universal - at least to my way of thinking. They only work with databases in the SQL Server family.
  • Universal Providers do not work with Simple Membership.
  • The Universal Providers packages include some web config transforms which you would normally want when you're using them.



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