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

European ASP.NET 4.5 Hosting - UK :: How to Use ListView Control in ASP.NET 4.5

clock July 24, 2014 08:49 by author Scott

ASP.NET 4.5 offer many great feature. Previously, we have discussed about one of new feature on ASP.NET 4.5, Key HTML Editor Features in ASP.NET 4.5. In today post, we will discuss about how to use ListView Control in ASP.NET 4.5

ASP.NET ListView Control has a great features that GridView and Repeater controls had control over the markup. The ListView Control allows you to display the data in various formats including grid format, bulleted list format and in flow format.

How to Insert and Delete Data with the ListView Control

OK, let’s get started

1. Drag the ListView control from data category of the toolbox to default.aspx page and choose the datasource for the control as shown below

2. Configure ListView option from ListViewControl smart tags as shown below

Provide the template information by selecting the desired template and also it allows you to select style for control. It also allows you to enable operations such as inserting and updating.

3. Add some custom styling to the control by adding a class as shown below

<LayoutTemplate>
            <ul id="itemPlaceholderContainer" runat="server" class="ItemStyle">
                <li runat="server" id="itemPlaceholder" />
            </ul>
</LayoutTemplate>

4. Remove the Id columns from ItemTemplate as these mark-ups generated automatically when you configure the control and columns. Repeat the same for InsertItemTemplate.

5. Add the custom styles to item containers as below

.ItemStyle
{
  width: 800px;
  list-style-type:none;
  clear:both;
}

.ItemStyle li
{
  height: 300px;
 width:250px;
 float:left;
}
.ItemStyle li img
{
 width:180px;
margin: 10px 20px 10px 0;
}

6. Run your application and you’ll see the result

Hosting Your ASP.NET 4.5 Site with HostForLIFE.eu

If you need/looking for cheap and reliable ASP.NET 4.5 hosting with European server, you can rely on us. We have support the latest ASP.NET 4.5 on our shared hosting environment. You can always start from only €1.29/month to test drive your new ASP.NET 4.5 application. Why wait longer??



European ASP.NET 4.5 Cloud Hosting - Germany :: Claims-Based Security in ASP.NET 4.5

clock June 5, 2014 10:42 by author Scott

When you talk about authentication in ASP.NET you will most undoubtedly hear the mention of the MembershipProvider. I'm here to tell you not to go down that road. That road will only lead to tears and suffering. This post will help you understand and implement your ASP.NET authentication built on top of FormsAuthentication. I hope you take away that building this stuff is not hard as long as you don't try to over think it.

Before I show you how to implement a kick-butt authentication system, I'll show you the simplest solution you could build.

FormsAuthentication.SetAuthCookie(user.Id, createPersistentCookie: true);

Congratulations you are now officially signed into your ASP.NET application using forms authentication. Notice I don't have any SQL migrations, crazy classes, or any other crap you didn't ask for.

 

The code above writes a cookie to the response of the current HttpContext. On the user's next request that cookie will be passed back to the server and used to check whether they are authenticated or not.

Password Hasher

Hashing passwords is really easy with .NET. The trick is to generate a salt with every password. The idea of the salt is not to be a secret, but to be unique every time. This makes it difficult for hackers to process all your passwords in the case your system is compromised. This is my standard password hasher:

public static class PasswordHasher {
    private const int SaltSize = 64;

    public static Passphrase Hash(string password) {
        if (password == null) throw new ArgumentNullException("password");

        byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
        byte[] saltBytes = CreateRandomSalt();
        string hashedPassword = ComputeHash(passwordBytes, saltBytes);

        return new Passphrase {
            Hash = hashedPassword,
            // Convert salt from byte[] to string
            Salt = Convert.ToBase64String(saltBytes)
        };
    }

    public static bool Equals(string password, string salt, string hash) {
        return String.CompareOrdinal(hash, Hash(password, salt)) == 0;
    }

    public static string GenerateRandomSalt(int size = SaltSize) {
        return Convert.ToBase64String(CreateRandomSalt(size));
    }

    private static string ComputeHash(byte[] password, byte[] salt) {
        var passwordAndSalt = new byte[salt.Length + password.Length];

        Buffer.BlockCopy(salt, 0, passwordAndSalt, 0, salt.Length);
        Buffer.BlockCopy(password, 0, passwordAndSalt, salt.Length, password.Length);
        byte[] computedHash;
        using (HashAlgorithm algorithm = new SHA256Managed()) {
            computedHash = algorithm.ComputeHash(passwordAndSalt);
        }
        return Convert.ToBase64String(computedHash);
    }

    private static string Hash(string password, string salt) {
        return ComputeHash(Encoding.Unicode.GetBytes(password), Convert.FromBase64String(salt));
    }

    private static byte[] CreateRandomSalt(int size = SaltSize) {
        if (size <= 0)
            throw new ArgumentException("size must be greater than zero.");

        var saltBytes = new Byte[size];
        using (var rng = new RNGCryptoServiceProvider()) {
            rng.GetBytes(saltBytes);
        }
        return saltBytes;
    }
}

public class Passphrase {
    public string Hash { get; set; }
    public string Salt { get; set; }
}

Principal and Identity

The IPrincipal and IIdentity interfaces are crucial to authentication in .NET. If you have ever used HttpContext, WebForms, or ASP.NET MVC then you are using derivations of these interfaces. It usually comes in the guise of a User property. You don't have to implement these classes, you can always use the GenericPrincipal and GenericIdentity. I like to implement them myself, because it allows me to pass a bit more useful data around in the cookie (remember cookies have size limits).

Let's first look at the IPrinicipal implementation:

public class MuchoPrincipal : IPrincipal {
    private readonly MuchoIdentity _identity;

    public MuchoPrincipal(MuchoIdentity identity) {
        _identity = identity;
    }

    #region IPrincipal Members

    public bool IsInRole(string role) {
        return
            _identity.Roles.Any(
                current => string.Compare(current, role, StringComparison.InvariantCultureIgnoreCase) == 0);
    }

    public IIdentity Identity {
        get { return _identity; }
    }

    public MuchoIdentity Information {
        get { return _identity; }
    }

    public bool IsUser {
        get { return !IsGuest; }
    }

    public bool IsGuest {
        get { return IsInRole("guest"); }
    }

    #endregion
}

Next up is the IIdentity, just take a look:

public class MuchoIdentity : IIdentity {
    public MuchoIdentity(FormsAuthenticationTicket ticket) {
        if (ticket == null) {
            Name = "Guest";
            Roles = new List<string> { "guest" };
            return;
        }

        var data = JsonConvert.DeserializeObject<MuchoCookie>(ticket.UserData);

        if (data == null) {
            AsGuest();
            return;
        }

        Id = data.Id;
        FirstName = data.FirstName;
        LastName = data.LastName;
        Name = string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName)
                   ? data.Email
                   : "{0} {1}".With(FirstName, LastName);
        Email = data.Email;
        Roles = data.Roles ?? new List<string> { "user" };
        RememberMe = data.RememberMe;

        try {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById(data.TimeZone);
        } catch (Exception) {
            TimeZone = TimeZoneInfo.Utc;
        }
    }

    public MuchoIdentity(User user) {
        if (user == null) {
            AsGuest();
            return;
        }

        Id = user.Id;
        Email = user.Email;
        FirstName = user.FirstName;
        LastName = user.LastName;
        Name = string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName)
                   ? user.Email
                   : "{0} {1}".With(FirstName, LastName);

        try {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById(user.TimeZone);
        } catch (Exception) {
            TimeZone = TimeZoneInfo.Utc;
        }
        Roles = new List<string> { user.Role ?? "user" };
    }

    private void AsGuest() {
        Name = "Guest";
        Roles = new List<string> { "guest" };
    }

    public int Id { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public TimeZoneInfo TimeZone { get; set; }
    public bool RememberMe { get; set; }
    public IList<string> Roles { get; set; }

    #region IIdentity Members

    public string AuthenticationType {
        get { return "MuchoForms"; }
    }

    public bool IsAuthenticated {
        get { return !( Id == 0 || string.IsNullOrWhiteSpace(Email)); }
    }

    public string Name { get; protected set;

    #endregion
}

C is for Cookie

The cookie object is really just a data transfer object. Nothing really mind blowing here. I usually create a structure to store my useful information. Again, keep in mind the size limitations of a cookie which is about 4kb (4096 bytes).

public class MuchoCookie {
    public MuchoCookie() {
        Roles = new List<string>();
    }

    public int Id { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TimeZone { get; set; }
    public List<string> Roles { get; set; }
    public bool RememberMe { get; set; }
}

FormsAuthenticationService

FormsAuthentication is built right into ASP.NET, but I like to write a littler wrapper around it so I can test and inject it into other classes. Also I create the cookie from the previous section when a user successfully signs in.

public class FormsAuthenticationService : IFormsAuthenticationService {
    private readonly HttpContextBase _httpContext;

    public FormsAuthenticationService(HttpContextBase httpContext) {
        _httpContext = httpContext;
    }

    #region IFormsAuthenticationService Members

    public void SignIn(User user, bool createPersistentCookie) {
        if (user == null)
            throw new ArgumentNullException("user");

        var cookie = new MuchoCookie {
            Id = user.Id,
            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,
            RememberMe = createPersistentCookie,
            TimeZone = user.TimeZone,
            Roles = new List<string> { user.Role ?? "user" }
        };

        string userData = JsonConvert.SerializeObject(cookie);
        var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
                                                   DateTime.Now.Add(FormsAuthentication.Timeout),
                                                   createPersistentCookie, userData);
        string encTicket = FormsAuthentication.Encrypt(ticket);
        var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };

        _httpContext.Response.Cookies.Add(httpCookie);
    }

    public void SignOut() {
        // Not worth covering, has been tested by Microsoft
        FormsAuthentication.SignOut();
    }

    #endregion
}

Notice the SignIn method creates the cookie and just writes it to the response using FormsAuthentication. We are leveraging what ASP.NET gives us. There is no reason to reinvent the wheel when it comes to passing secure cookies to the client.

PrincipalService

The principal service helps us get the information out of a cookie and rehydrate our IPrinipal and our IIdentity to our custom implementations. The other added benefit is we can actually set the User property to a Guest principal with extra information if we need it.

public class MuchoSupportPrincipalService : IPrincipalService {
    private readonly HttpContextBase _context;

    public MuchoSupportPrincipalService(HttpContextBase context) {
        _context = context;
    }

    #region IPrincipalService Members

    public IPrincipal GetCurrent() {
        IPrincipal user = _context.User;
        // if they are already signed in, and conversion has happened
        if (user != null && user is MuchoPrincipal)
            return user;

        // if they are signed in, but conversion has still not happened
        if (user != null && user.Identity.IsAuthenticated && user.Identity is FormsIdentity) {
            var id = (FormsIdentity)_context.User.Identity;

            var ticket = id.Ticket;
            if (FormsAuthentication.SlidingExpiration) 
                ticket = FormsAuthentication.RenewTicketIfOld(ticket);

            var fid = new MuchoIdentity(ticket);
            return new MuchoPrincipal(fid);
        }

        // not sure what's happening, let's just default here to a Guest
        return new MuchoPrincipal(new MuchoIdentity((FormsAuthenticationTicket)null));
    }

    #endregion
}

The trick here is just to check the current context for the cookie already being passed in with our request. You need to call this code from your Global.asax as such (note I am using ASP.NET MVC and the dependency resolver built into it).

protected void Application_AuthenticateRequest(object sender, EventArgs e) {
    var principalService = DependencyResolver.Current.GetService<IPrincipalService>();
    var context = DependencyResolver.Current.GetService<HttpContextBase>();
    // Set the HttpContext's User to our IPrincipal
    context.User = principalService.GetCurrent();
}

Usage in Your Code

This is what my ASP.NET MVC controller looks like:

[RequireScheme(Scheme.Https)]
public class AuthenticationController : ApplicationController {
public ActionResult Login(string returnUrl) {

if (User.Identity.IsAuthenticated) {
if (!string.IsNullOrWhiteSpace(returnUrl))
return Redirect(returnUrl);

return RedirectToAction("show", "dashboard");
}

var model = new LoginModel {
ReturnUrl = returnUrl
};

return View(model);
}

[HttpPost]
public ActionResult Login(LoginModel input) {
// validation does password hash check
// you could do it more explicitly
if (ModelState.IsValid) {
Logger.Info("successful!", input.Username);
var user = Db.Users
.FirstOrDefault(u => u.Email == input.Username);
// set cookie
Forms.SignIn(user, input.RememberMe);
return input.HasReturnUrl(Url)
? Redirect(input.ReturnUrl)
: (ActionResult) RedirectToAction("show", "dashboard");
}

Flash.Error("Please try again");

return View("login", input);
}

public ActionResult Logout() {
Forms.SignOut();
return RedirectToAction("login");
}
}

Conclusion

The parts of an authentication system are all infrastructural. It is all smooth sailing once you get over the hump of setting it up. Once the infrastructure is set up you can work on creating your own tables for Users, Profiles, or any other domain model that makes sense. All access to user's is up to you, so feel free to use any data access provider you like: SQL Server, RavenDB, MongoDB, etc. Additionally, the cookie is now yours; feel free to add or remove data from it as you see fit, but always remember the 4kb size limit.



European ASP.NET 4.5 Hosting - Amsterdam :: ASP.Net 4.5 Strongly Typed Data Controls and Visual Studio 2012

clock June 25, 2013 06:46 by author Scott

In this post I will show you one of great features in ASP.NET 4.5, it is called Strongly Typed Data controls in ASP.NET 4.5.

I will be demonstrating with a hands-on example on Strongly Typed Data controls and how we can have Intellisense and compile type checking using this new feature.

I assume you have downloaded VS 2012 (Express edition will do).I have also downloaded and installed AdventureWorksLT2012 database.You can download this database from the codeplex website.

I will be creating a simple website without using this feature. Then I will show you what the problem is without using this feature.

1) Launch VS 2012. Create a new ASP.Net Web Forms Site. Choose C# as the development language.Give an appropriate name to your site.

2) Now we will add a data access layer to our site in order to fetch some data to the user interface.I will use EF database first approach.

3) Add a new item in your project, an ADO.Net Entity Data Model. I have named it AdventureWorksLT.edmx.Then we will create the model from the database and click Next.Create a new connection by specifying the SQL Server instance and the database name and click OK.Then click Next in the wizard.In the next screen of the wizard select only the Customer table from the database and hit Finish.You will see the Customer entity in the Entity Designer. 

4) Add a new web form to your site.Name is Customer.aspx.We will add a new web server control a GridView that will get the data from the database through EF.

This is the code for the web server control.I am using the Bind syntax.We are using strings to represent the property names (FirstName,LastName).

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

            <Columns>
                <asp:TemplateField HeaderText="FirstName">
                   
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                    </ItemTemplate>
               
               </asp:TemplateField>
               
               <asp:TemplateField HeaderText="LastName">
                   

                     <ItemTemplate>
    <asp:Label ID="lbName" runat="server" Text='<%# Bind("LastName")
%>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

5) In the Page_Load event handling routine of the Customer.aspx page type the following code

        AdventureWorks2012Entities ctx = new AdventureWorks2012Entities();

        var query = from cust in ctx.Customers
     
        select new {cust.FirstName,cust.LastName};

        GridView1.DataSource = query.ToList();

        GridView1.DataBind();

6)  Build and Run the application. You will see the data appearing on the page.

7) Now let's do a simple typo.Replace the following line

<asp:Label ID="lbName" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>

with this

<asp:Label ID="lbName" runat="server" Text='<%# Bind("LLastName") %>'></asp:Label>

Build your site. It will compile. The compiler does not know anything . Guess where you will get the exception, at runtime.Run your site and you will get an exception.

8) Let's rewrite the code in the Customers.aspx page.

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ItemType="AdventureWorks2012Entities.Customer">

            <Columns>
                <asp:TemplateField HeaderText="FirstName">

                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Item.FirstName %>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="LastName">

                    <ItemTemplate>
                        <asp:Label ID="lbName" runat="server" Text='<%# Item.LastName %>'></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

Now we can tell our application what type of data the control will be bound to using the ItemType 

ItemType="AdventureWorks2012Entities.Customer"

Now we need to alter the code in the template. Have a look at those 2 lines 

  <asp:Label ID="lblName" runat="server" Text='<%# Item.FirstName %>'></asp:Label>
  <asp:Label ID="lbName" runat="server" Text='<%# Item.LastName %>'></asp:Label> 

Now we have compile type checking and Intellisense in our sample application.As we type the compiler informs us if it recognizes the property. This is a great enhancement since I do not want to face exceptions on runtime because of typos. 

9) Build and run your application again. The sample application works fine.

 



European ASP.NET 4.5 Hosting - Amsterdam :: Creating Custom Value Provider in ASP.NET 4.5

clock May 30, 2013 07:46 by author Scott

With ASP.NET 4.5, ASP.NET introduced model binding for web forms as well. Model binding helps to simplify code focused data access logic within web forms.

Here in this post, we will see how we can create our own custom value provider. We will also examine inbuilt class of ASP.NET 4.5 model binding framework which can be useful in creating custom value provider more easily with focused approach.

Before we look into actual interfaces and classes, let us examine few basics of model binding framework. All model binding framework and corresponding classes are resides in System.Web.ModelBinding namespace which is newly introduced with ASP.NET 4.5. For any value provider to work with model binder it requires two components one is implementation of value provider which reads data from request and forward it to model binder and other one is value provider source attribute which expose the actual value provider instance. Have a look at below code snippet here QueryStringAttribute is value provider source attribute which expose object of QueryStringValueProvider so model binder can use it to fetch data.

public IQueryable<Blog> SelectMethod([QueryString]int? id)

Creating Value Provider Source Attribute

To create custom value provider attribute we can derive Attribute class and implement IValueProviderSource interface as displayed in below code snippet.

public class CustomValueProviderAttribute : Attribute, IValueProviderSource
{
    public IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        return new CustomValueProvider(modelBindingExecutionContext);
    }
}

Here we can have access of ModelBindingExecutionContext and we can pass same to value provider if it is required. Through ModelBindingExecutionContext we can also have access of HttpContextBase and ModelStateDictionary.

Creating Value Provider

Same way we can create Custom Value Provider by implementing IValueProvider interface. Below code snippet shows pseudo code for the same.

public class CustomValueProvider : IValueProvider
{
    ModelBindingExecutionContext _modelBindingExecutionContext;

    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
    {
        this._modelBindingExecutionContext = modelBindingExecutionContext;
    } 

    public bool ContainsPrefix(string prefix)
    {
        // validate if requested key is exist or not
    } 

    public ValueProviderResult GetValue(string key)
    {
        // return ValueProviderResult object we
        // can use ModelBindingExecutionContext
        // to access request data
    }
}

Once we are ready we can use created value provider as

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

As noted earlier, there are few inbuilt classes in ASP.NET 4.5 model binding framework which give more focused control over custom business logic. Here we will also examine one of its which is SimpleValueProvider. Here we will examine how we can focus on core logic and leaving other responsibility on core framework.

public class CustomValueProvider : SimpleValueProvider
{
    public CustomValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
        : base(modelBindingExecutionContext)
    {
    } 

    protected override object FetchValue(string key)
    {
        // here we can access this.ModelBindingExecutionContext
        // and can look into request data. Once we fetch requested
        // data we just need to return actual value for e.g.           
        return "dotnetExpertGuide.com";
        // NOTE: WE ARE NOT RETURNING ValueProviderResult INSTANCE
    }
}

Earlier with IValueProvider, we had to check if requested key exist or not and if it is then instantiating ValueProviderResult and return it. While with SimpleValueProvider we only need to return actual value of requested key or null incase if it does not exist rest will be taken care by SimpleValueProvider class. Another such framework class is NameValueCollectionValueProvider which act as a base class to create value provider from name value collection. Here I am not demonstrating it. I am leaving it for reader :).

SimpleValueProvider and ASP.NET MVC

Can’t we have/introduce SimpleValueProvider class for MVC in upcoming version?

ModelStateDictionary

Once model binding is done for parameter it is added to ModelStateDictionary dictionary along with its value. For e.g.

SelectMethod([CustomValueProvider]int? id, [CustomValueProvider]string name)

In above code once model binding is done for parameter id, it is added to ModelStateDictionary and it is accessible in rest of the parameter model binding i.e. parameter name here.

 



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in