Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

We’re showing branches in this repository, but you can also compare across forks.

base fork: jtuckr/modernizr-server-dotnet
base: cb289c6511
...
head fork: jtuckr/modernizr-server-dotnet
compare: baaed84b48
  • 3 commits
  • 21 files changed
  • 0 commit comments
  • 1 contributor
9 LICENSE
View
@@ -0,0 +1,9 @@
+MIT License:
+
+Copyright (c) 2012 Justin Tucker
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 Modernizr-Server.sln
View
@@ -0,0 +1,20 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Web Developer Express 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernizrServer", "Modernizr-Server\ModernizrServer.csproj", "{1BD18F12-92D6-4AAF-B799-0F82E61863E1}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {1BD18F12-92D6-4AAF-B799-0F82E61863E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1BD18F12-92D6-4AAF-B799-0F82E61863E1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1BD18F12-92D6-4AAF-B799-0F82E61863E1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1BD18F12-92D6-4AAF-B799-0F82E61863E1}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
26 Modernizr-Server/Default.aspx
View
@@ -0,0 +1,26 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ModernizrServer.Default" %>
+
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+ <title>Modernizr Server</title>
+</head>
+<body>
+ <form id="form1" runat="server">
+ <div>
+ <h1>Modernizr Server</h1>
+ <p>Modernizr Server allows for an application to access browser capabilities detected
+ by Modernizr in server-side code.</p>
+
+ <h2>Usage</h2>
+ <p>Include the ModernizrCookie.aspx page in your application, as well as the logic
+ found in the code-behind of this page. See the <a href="VideoTest.aspx">Video Test</a>
+ page for sample usage.</p>
+
+ <h2>Modernizr Features</h2>
+ <p>See a <a href="ModernizrTestPage.aspx">full list of the features</a> detected by
+ Modernizr and which of those your browser supports!</p>
+ </div>
+ </form>
+</body>
+</html>
129 Modernizr-Server/Default.aspx.cs
View
@@ -0,0 +1,129 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+using System.Text;
+using System.Dynamic;
+
+namespace ModernizrServer
+{
+ public partial class Default : System.Web.UI.Page
+ {
+ //Configurable private members
+ private string _key = "Modernizr";
+ private int _MaxCookieAttempts = 3;
+
+ /// <summary>
+ /// The magic behind Modernizr-Server
+ /// </summary>
+ /// <param name="sender"></param>
+ /// <param name="e"></param>
+ protected void Page_Load(object sender, EventArgs e)
+ {
+ if (Session[_key] != null && !String.IsNullOrEmpty(Session[_key].ToString()))
+ {
+ // The Modernizr object is in session and ready to use
+ dynamic Modernizr = Session[_key];
+
+ if (Modernizr != null)
+ {
+ // At this point you are ready to test a particular property
+ // and do something with it
+
+ }
+ else
+ {
+ // The Modernizr object cannot be retrieved from session.
+ //
+ // A workaround needs to be put here for this case.
+ // Ex: load a javascript file that checks the modernizr
+ // capability client-side and does something with it
+ }
+ }
+ else
+ {
+ // This is likely a new session...
+ //
+ // Check to see if a Modernizr cookie has been set
+ HttpCookieCollection TheCookies = Request.Cookies;
+ HttpCookie ModernizrCookie = TheCookies.Get(_key);
+ if (ModernizrCookie != null)
+ {
+ // Build the dynamic object from cookie found on user's machine
+ dynamic ModernizrDynamic = new ExpandoObject();
+ string[] FeatureArray = ModernizrCookie.Value.Split('|');
+ // Feature Array would look something like [ cssgradients:1, draganddrop:0, ....]
+ string[] FeatureKeyValueArray = new string[2];
+ foreach (string Feature in FeatureArray)
+ {
+ if (!String.IsNullOrWhiteSpace(Feature))
+ {
+ FeatureKeyValueArray = Feature.Split(new[] { ':' }, 2);
+ // FeatureKeyValueArray could be a simply property like [cssgradients,1]
+ // but it could be a more complicated property like [video,/ogg:1/webm:0/h264:1]
+ var f = ModernizrDynamic as IDictionary<String, object>;
+ if (FeatureKeyValueArray[1].StartsWith("/"))
+ {
+ dynamic ValueObject = new ExpandoObject();
+ string[] SubFeatureArray = FeatureKeyValueArray[1].Trim('/').Split('/');
+ //SubFeatureArray would be [ogg:1,webm:1,h264:1]
+ foreach (string SubFeature in SubFeatureArray)
+ {
+ string[] SubFeatureKeyValueArray = SubFeature.Split(new[] { ':' }, 2);
+ //SubFeatureKeyValueArray would be [ogg,1]
+ var v = ValueObject as IDictionary<String, object>;
+ //change the 0 or 1 to false or true so that boolean logic can be used
+ v[SubFeatureKeyValueArray[0]] = SubFeatureKeyValueArray[1] == "0" ? false : true;
+ }
+ f[FeatureKeyValueArray[0]] = ValueObject;
+ }
+ else
+ {
+ //change the 0 or 1 to false or true so that boolean logic can be used
+ f[FeatureKeyValueArray[0]] = FeatureKeyValueArray[1] == "0" ? false : true;
+ }
+ }
+ }
+ // Store the generated object in session for later use
+ Session[_key] = ModernizrDynamic;
+ }
+ else
+ {
+ // No Modernizr cookie exists, so we need to try to create one
+ if (Session["ModernizrCookieAttempts"] == null)
+ {
+ // ModernizrCookie has not been called before during this session
+ Session["ModernizrCookieAttempts"] = 1;
+ Response.Redirect("ModernizrCookie.aspx");
+ }
+ else
+ {
+ // ModernizrCookie has been called before during this session and was
+ // unsuccessful, or the user cleared their cookies during the session
+ // AND the session object was also lost. The latter would be unlikely,
+ // but I guess it's possible...
+ int CookieAttempts = int.Parse(Session["ModernizrCookieAttempts"].ToString());
+ if (CookieAttempts <= _MaxCookieAttempts)
+ {
+ CookieAttempts++;
+ Session["ModernizrCookieAttempts"] = CookieAttempts;
+ Response.Redirect("ModernizrCookie.aspx");
+ }
+ else
+ {
+ // The application has tried several times (depending on
+ // the configured "MaxCookieAttempts" variable) during this session
+ // to set a cookie and has been unsuccessful.
+ //
+ // A workaround needs to be put here for these cases.
+ // Ex: load a javascript file that checks the modernizr
+ // capability client-side and does something with it
+ }
+ }
+ }
+ }
+ }
+ }
+}
48 Modernizr-Server/ModernizrCookie.aspx
View
@@ -0,0 +1,48 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ModernizrCookie.aspx.cs" Inherits="ModernizrServer.ModernizrCookie" %>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+ <title></title>
+ <script src="js/modernizr.js" type="text/javascript"></script>
+</head>
+<body>
+ <form id="form1" runat="server"></form>
+ <script>
+ window.onload = function () {
+ var m = Modernizr,
+ f,
+ t,
+ c = '',
+ dt,
+ expires;
+ dt = new Date();
+ dt.setTime(dt.getTime() + (1 * 24 * 60 * 60 * 1000));
+ expires = "; expires=" + dt.toGMTString(); ;
+ for (f in m) {
+ if (f[0] == '_') {
+ continue
+ }
+ t = typeof m[f];
+ if (t == 'function') {
+ continue
+ }
+ c += (c ? '|' : 'Modernizr=') + f + ':';
+ if (t == 'object') {
+ for (var s in m[f]) {
+ c += '/' + s + ':' + (m[f][s] ? '1' : '0')
+ }
+ } else {
+ c += m[f] ? '1' : '0'
+ }
+ }
+ c += ';path=/';
+ try {
+ document.cookie = c + expires;
+ } catch (e) { }
+ window.top.location = 'default.aspx';
+ };
+ </script>
+</body>
+</html>
18 Modernizr-Server/ModernizrCookie.aspx.cs
View
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+using System.Text;
+using System.IO;
+
+namespace ModernizrServer
+{
+ public partial class ModernizrCookie : System.Web.UI.Page
+ {
+ protected void Page_Load(object sender, EventArgs e)
+ {
+ }
+ }
+}
122 Modernizr-Server/ModernizrServer.csproj
View
@@ -0,0 +1,122 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>
+ </ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{1BD18F12-92D6-4AAF-B799-0F82E61863E1}</ProjectGuid>
+ <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>ModernizrServer</RootNamespace>
+ <AssemblyName>Modernizr-Server</AssemblyName>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <UseIISExpress>false</UseIISExpress>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="System.Web.Extensions" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Drawing" />
+ <Reference Include="System.Web" />
+ <Reference Include="System.Xml" />
+ <Reference Include="System.Configuration" />
+ <Reference Include="System.Web.Services" />
+ <Reference Include="System.EnterpriseServices" />
+ <Reference Include="System.Web.DynamicData" />
+ <Reference Include="System.Web.Entity" />
+ <Reference Include="System.Web.ApplicationServices" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="Default.aspx" />
+ <Content Include="js\modernizr.js" />
+ <Content Include="ModernizrCookie.aspx" />
+ <Content Include="ModernizrTestPage.aspx" />
+ <Content Include="VideoTest.aspx" />
+ <Content Include="Web.config" />
+ <Content Include="Web.Debug.config">
+ <DependentUpon>Web.config</DependentUpon>
+ </Content>
+ <Content Include="Web.Release.config">
+ <DependentUpon>Web.config</DependentUpon>
+ </Content>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="VideoTest.aspx.cs">
+ <DependentUpon>VideoTest.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Compile>
+ <Compile Include="VideoTest.aspx.designer.cs">
+ <DependentUpon>VideoTest.aspx</DependentUpon>
+ </Compile>
+ <Content Include="Default.aspx.cs">
+ <DependentUpon>Default.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Content>
+ <Content Include="ModernizrCookie.aspx.cs">
+ <DependentUpon>ModernizrCookie.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Content>
+ <Content Include="ModernizrTestPage.aspx.cs">
+ <DependentUpon>ModernizrTestPage.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Content>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="assets\video\h.264\gizmo.mp4" />
+ <None Include="assets\video\ogg\gizmo.ogv" />
+ <None Include="assets\video\webm\gizmo.webm" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
+ <ProjectExtensions>
+ <VisualStudio>
+ <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
+ <WebProjectProperties>
+ <UseIIS>False</UseIIS>
+ <AutoAssignPort>True</AutoAssignPort>
+ <DevelopmentServerPort>4657</DevelopmentServerPort>
+ <DevelopmentServerVPath>/</DevelopmentServerVPath>
+ <IISUrl>
+ </IISUrl>
+ <NTLMAuthentication>False</NTLMAuthentication>
+ <UseCustomServer>False</UseCustomServer>
+ <CustomServerUrl>
+ </CustomServerUrl>
+ <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
+ </WebProjectProperties>
+ </FlavorProperties>
+ </VisualStudio>
+ </ProjectExtensions>
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
15 Modernizr-Server/ModernizrTestPage.aspx
View
@@ -0,0 +1,15 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ModernizrTestPage.aspx.cs" Inherits="ModernizrServer.ModernizrTestPage" %>
+
+<!DOCTYPE html>
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+ <title>Modernizr Server - All Features Detected</title>
+</head>
+<body>
+ <form id="form1" runat="server">
+ <div id="ModernizrResults" runat="server">
+ </div>
+ </form>
+</body>
+</html>
46 Modernizr-Server/ModernizrTestPage.aspx.cs
View
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+using System.Text;
+
+namespace ModernizrServer
+{
+ public partial class ModernizrTestPage : System.Web.UI.Page
+ {
+ protected void Page_Load(object sender, EventArgs e)
+ {
+ dynamic ModernizrDynamic = Session["Modernizr"];
+
+ // For testing purposes only - print out all of the key/value objects
+ // within the Modernizr object
+ IDictionary<string, object> ModernizrDict = (IDictionary<string, object>)ModernizrDynamic;
+ IDictionary<string, object> ModernizrSubDict;
+ StringBuilder sb = new StringBuilder();
+ sb.Append("<p>Modernizr values found:</p><ul>");
+ foreach (var kvp in ModernizrDict)
+ {
+ sb.AppendFormat("<li>{0}:", kvp.Key);
+ if (kvp.Value.GetType() == typeof(bool))
+ {
+ sb.Append(kvp.Value.ToString());
+ }
+ else
+ {
+ sb.Append("<ul>");
+ ModernizrSubDict = (IDictionary<string, object>)kvp.Value;
+ foreach (var subkvp in ModernizrSubDict)
+ {
+ sb.AppendFormat("<li>{0}:{1}</li>", subkvp.Key, subkvp.Value.ToString());
+ }
+ sb.Append("</ul>");
+ }
+ sb.Append("</li>");
+ }
+ sb.Append("</ul>");
+ ModernizrResults.InnerHtml = sb.ToString();
+ }
+ }
+}
35 Modernizr-Server/Properties/AssemblyInfo.cs
View
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Modernizr_Server")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Modernizr_Server")]
+[assembly: AssemblyCopyright("")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("87d8ab86-def2-4600-8ba8-205c4ad2af30")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Revision and Build Numbers
+// by using the '*' as shown below:
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
22 Modernizr-Server/VideoTest.aspx
View
@@ -0,0 +1,22 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VideoTest.aspx.cs" Inherits="ModernizrServer.VideoTest" %>
+
+<!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>Modernizr Server - Video Test</title>
+</head>
+<body>
+ <form id="form1" runat="server">
+ <div>
+ <h1>Modernizr Video Test</h1>
+ <p>A sample video page that demonstrates how Modernizr Server would test
+ for video support and include the appropriate source(s). Video samples are from
+ <a href="http://www.808.dk/?code-html-5-video">808.dk</a> and are for demonstration
+ purposes only.</p>
+ <p><strong><asp:Literal ID="VideoCapabilities" runat="server"></asp:Literal></strong></p>
+ <asp:PlaceHolder ID="VideoPlaceHolder" runat="server"></asp:PlaceHolder>
+ </div>
+ </form>
+</body>
+</html>
69 Modernizr-Server/VideoTest.aspx.cs
View
@@ -0,0 +1,69 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+using System.Web.UI.HtmlControls;
+
+namespace ModernizrServer
+{
+ public partial class VideoTest : System.Web.UI.Page
+ {
+ protected void Page_Load(object sender, EventArgs e)
+ {
+ dynamic Modernizr = Session["Modernizr"];
+
+ if (Modernizr != null)
+ {
+ if (Modernizr.video != null)
+ {
+ HtmlGenericControl VideoControl = new HtmlGenericControl("video");
+ VideoControl.Attributes.Add("autoplay", "autoplay");
+ VideoControl.Attributes.Add("controls", "controls");
+ if (Modernizr.video.h264)
+ {
+ VideoCapabilities.Text += "Your browser supports h.264. ";
+ HtmlGenericControl VideoSource = new HtmlGenericControl("source");
+ VideoSource.Attributes.Add("src", "assets/video/h.264/gizmo.mp4");
+ VideoControl.Controls.Add(VideoSource);
+ }
+ if (Modernizr.video.webm)
+ {
+ VideoCapabilities.Text += "Your browser supports webm. ";
+ HtmlGenericControl VideoSource = new HtmlGenericControl("source");
+ VideoSource.Attributes.Add("src", "assets/video/webm/gizmo.webm");
+ VideoSource.Attributes.Add("type", "video/webm");
+ VideoControl.Controls.Add(VideoSource);
+ }
+ if (Modernizr.video.ogg)
+ {
+ VideoCapabilities.Text += "Your browser supports ogg. ";
+ HtmlGenericControl VideoSource = new HtmlGenericControl("source");
+ VideoSource.Attributes.Add("src", "assets/video/ogg/gizmo.ogv");
+ VideoSource.Attributes.Add("type", "video/ogg");
+ VideoControl.Controls.Add(VideoSource);
+ }
+ else
+ {
+ VideoCapabilities.Text = "Your browser does not support h.264, webm or ogg video formats";
+ }
+ VideoPlaceHolder.Controls.Add(VideoControl);
+ }
+ else
+ {
+ VideoCapabilities.Text = "Your browser does not support h.264, webm or ogg video formats";
+ }
+ // End Example
+ }
+ else
+ {
+ // The Modernizr object cannot be retrieved from session.
+ //
+ // A workaround needs to be put here for this case.
+ // Ex: load a javascript file that checks the modernizr
+ // capability client-side and does something with it
+ }
+ }
+ }
+}
42 Modernizr-Server/VideoTest.aspx.designer.cs
View
@@ -0,0 +1,42 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace ModernizrServer {
+
+
+ public partial class VideoTest {
+
+ /// <summary>
+ /// form1 control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.HtmlControls.HtmlForm form1;
+
+ /// <summary>
+ /// VideoCapabilities control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Literal VideoCapabilities;
+
+ /// <summary>
+ /// VideoPlaceHolder control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.PlaceHolder VideoPlaceHolder;
+ }
+}
30 Modernizr-Server/Web.Debug.config
View
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+
+<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
+
+<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
+ <!--
+ In the example below, the "SetAttributes" transform will change the value of
+ "connectionString" to use "ReleaseSQLServer" only when the "Match" locator
+ finds an atrribute "name" that has a value of "MyDB".
+
+ <connectionStrings>
+ <add name="MyDB"
+ connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
+ xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
+ </connectionStrings>
+ -->
+ <system.web>
+ <!--
+ In the example below, the "Replace" transform will replace the entire
+ <customErrors> section of your web.config file.
+ Note that because there is only one customErrors section under the
+ <system.web> node, there is no need to use the "xdt:Locator" attribute.
+
+ <customErrors defaultRedirect="GenericError.htm"
+ mode="RemoteOnly" xdt:Transform="Replace">
+ <error statusCode="500" redirect="InternalError.htm"/>
+ </customErrors>
+ -->
+ </system.web>
+</configuration>
31 Modernizr-Server/Web.Release.config
View
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+
+<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
+
+<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
+ <!--
+ In the example below, the "SetAttributes" transform will change the value of
+ "connectionString" to use "ReleaseSQLServer" only when the "Match" locator
+ finds an atrribute "name" that has a value of "MyDB".
+
+ <connectionStrings>
+ <add name="MyDB"
+ connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
+ xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
+ </connectionStrings>
+ -->
+ <system.web>
+ <compilation xdt:Transform="RemoveAttributes(debug)" />
+ <!--
+ In the example below, the "Replace" transform will replace the entire
+ <customErrors> section of your web.config file.
+ Note that because there is only one customErrors section under the
+ <system.web> node, there is no need to use the "xdt:Locator" attribute.
+
+ <customErrors defaultRedirect="GenericError.htm"
+ mode="RemoteOnly" xdt:Transform="Replace">
+ <error statusCode="500" redirect="InternalError.htm"/>
+ </customErrors>
+ -->
+ </system.web>
+</configuration>
20 Modernizr-Server/Web.config
View
@@ -0,0 +1,20 @@
+<?xml version="1.0"?>
+
+<!--
+ For more information on how to configure your ASP.NET application, please visit
+ http://go.microsoft.com/fwlink/?LinkId=169433
+ -->
+
+<configuration>
+ <connectionStrings />
+ <system.web>
+ <compilation debug="false" targetFramework="4.0" />
+ <authentication mode="Windows">
+ </authentication>
+ <sessionState mode="InProc" cookieless="false" timeout="30" />
+ </system.web>
+
+ <system.webServer>
+ <modules runAllManagedModulesForAllRequests="true"/>
+ </system.webServer>
+</configuration>
BIN  Modernizr-Server/assets/video/h.264/gizmo.mp4
View
Binary file not shown
BIN  Modernizr-Server/assets/video/ogg/gizmo.ogv
View
Binary file not shown
BIN  Modernizr-Server/assets/video/webm/gizmo.webm
View
Binary file not shown
1  Modernizr-Server/js/modernizr.js
View
@@ -0,0 +1 @@
+window.Modernizr = (function (window, document, undefined) { var version = '2.5.3', Modernizr = {}, enableClasses = true, docElement = document.documentElement, mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, inputElem = document.createElement('input'), smile = ':)', toString = {}.toString, prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), ns = { 'svg': 'http://www.w3.org/2000/svg' }, tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, injectElementWithStyles = function (rule, callback, nodes, testnames) { var style, ret, node, div = document.createElement('div'), body = document.body, fakeBody = body ? body : document.createElement('body'); if (parseInt(nodes, 10)) { while (nodes--) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node) } } style = ['&#173;', '<style>', rule, '</style>'].join(''); div.id = mod; fakeBody.innerHTML += style; fakeBody.appendChild(div); if (!body) { fakeBody.style.background = ""; docElement.appendChild(fakeBody) } ret = callback(div, rule); !body ? fakeBody.parentNode.removeChild(fakeBody) : div.parentNode.removeChild(div); return !!ret }, testMediaQuery = function (mq) { var matchMedia = window.matchMedia || window.msMatchMedia; if (matchMedia) { return matchMedia(mq).matches } var bool; injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function (node) { bool = (window.getComputedStyle ? getComputedStyle(node, null) : node.currentStyle)['position'] == 'absolute' }); return bool }, isEventSupported = (function () { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported(eventName, element) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; var isSupported = eventName in element; if (!isSupported) { if (!element.setAttribute) { element = document.createElement('div') } if (element.setAttribute && element.removeAttribute) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); if (!is(element[eventName], 'undefined')) { element[eventName] = undefined } element.removeAttribute(eventName) } } element = null; return isSupported } return isEventSupported })(); var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty; if (!is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined')) { hasOwnProperty = function (object, property) { return _hasOwnProperty.call(object, property) } } else { hasOwnProperty = function (object, property) { return ((property in object) && is(object.constructor.prototype[property], 'undefined')) } } if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function () { }; F.prototype = target.prototype; var self = new F; var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result } return self } else { return target.apply(that, args.concat(slice.call(arguments))) } }; return bound } } function setCss(str) { mStyle.cssText = str } function setCssAll(str1, str2) { return setCss(prefixes.join(str1 + ';') + (str2 || '')) } function is(obj, type) { return typeof obj === type } function contains(str, substr) { return !! ~('' + str).indexOf(substr) } function testProps(props, prefixed) { for (var i in props) { if (mStyle[props[i]] !== undefined) { return prefixed == 'pfx' ? props[i] : true } } return false } function testDOMProps(props, obj, elem) { for (var i in props) { var item = obj[props[i]]; if (item !== undefined) { if (elem === false) return props[i]; if (is(item, 'function')) { return item.bind(elem || obj) } return item } } return false } function testPropsAll(prop, prefixed, elem) { var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); if (is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed) } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem) } } var testBundle = (function (styles, tests) { var style = styles.join(''), len = tests.length; injectElementWithStyles(style, function (node, rule) { var style = document.styleSheets[document.styleSheets.length - 1], cssText = style ? (style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || '') : '', children = node.childNodes, hash = {}; while (len--) { hash[children[len].id] = children[len] } Modernizr['touch'] = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch || (hash['touch'] && hash['touch'].offsetTop) === 9; Modernizr['csstransforms3d'] = (hash['csstransforms3d'] && hash['csstransforms3d'].offsetLeft) === 9 && hash['csstransforms3d'].offsetHeight === 3; Modernizr['generatedcontent'] = (hash['generatedcontent'] && hash['generatedcontent'].offsetHeight) >= 1; Modernizr['fontface'] = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0 }, len, tests) })(['@font-face {font-family:"font";src:url("https://")}', ['@media (', prefixes.join('touch-enabled),('), mod, ')', '{#touch{top:9px;position:absolute}}'].join(''), ['@media (', prefixes.join('transform-3d),('), mod, ')', '{#csstransforms3d{left:9px;position:absolute;height:3px;}}'].join(''), ['#generatedcontent:after{content:"', smile, '";visibility:hidden}'].join('')], ['fontface', 'touch', 'csstransforms3d', 'generatedcontent']); tests['flexbox'] = function () { return testPropsAll('flexOrder') }; tests['flexbox-legacy'] = function () { return testPropsAll('boxDirection') }; tests['canvas'] = function () { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')) }; tests['canvastext'] = function () { return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')) }; tests['webgl'] = function () { try { var canvas = document.createElement('canvas'), ret; ret = !!(window.WebGLRenderingContext && (canvas.getContext('experimental-webgl') || canvas.getContext('webgl'))); canvas = undefined } catch (e) { ret = false } return ret }; tests['touch'] = function () { return Modernizr['touch'] }; tests['geolocation'] = function () { return !!navigator.geolocation }; tests['postmessage'] = function () { return !!window.postMessage }; tests['websqldatabase'] = function () { return !!window.openDatabase }; tests['indexedDB'] = function () { return !!testPropsAll("indexedDB", window) }; tests['hashchange'] = function () { return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7) }; tests['history'] = function () { return !!(window.history && history.pushState) }; tests['draganddrop'] = function () { var div = document.createElement('div'); return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div) }; tests['websockets'] = function () { for (var i = -1, len = cssomPrefixes.length; ++i < len; ) { if (window[cssomPrefixes[i] + 'WebSocket']) { return true } } return 'WebSocket' in window }; tests['rgba'] = function () { setCss('background-color:rgba(150,255,150,.5)'); return contains(mStyle.backgroundColor, 'rgba') }; tests['hsla'] = function () { setCss('background-color:hsla(120,40%,100%,.5)'); return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla') }; tests['multiplebgs'] = function () { setCss('background:url(https://),url(https://),red url(https://)'); return /(url\s*\(.*?){3}/.test(mStyle.background); }; tests['backgroundsize'] = function () { return testPropsAll('backgroundSize'); }; tests['borderimage'] = function () { return testPropsAll('borderImage'); }; tests['borderradius'] = function () { return testPropsAll('borderRadius'); }; tests['boxshadow'] = function () { return testPropsAll('boxShadow'); }; tests['textshadow'] = function () { return document.createElement('div').style.textShadow === ''; }; tests['opacity'] = function () { setCssAll('opacity:.55'); return /^0.55$/.test(mStyle.opacity) }; tests['cssanimations'] = function () { return testPropsAll('animationName') }; tests['csscolumns'] = function () { return testPropsAll('columnCount') }; tests['cssgradients'] = function () { var str1 = 'background-image:', str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', str3 = 'linear-gradient(left top,#9f9, white);'; setCss((str1 + '-webkit- '.split(' ').join(str2 + str1) + prefixes.join(str3 + str1)).slice(0, -str1.length)); return contains(mStyle.backgroundImage, 'gradient') }; tests['cssreflections'] = function () { return testPropsAll('boxReflect') }; tests['csstransforms'] = function () { return !!testPropsAll('transform') }; tests['csstransforms3d'] = function () { var ret = !!testPropsAll('perspective'); if (ret && 'webkitPerspective' in docElement.style) { ret = Modernizr['csstransforms3d'] } return ret }; tests['csstransitions'] = function () { return testPropsAll('transition') }; tests['fontface'] = function () { return Modernizr['fontface'] }; tests['generatedcontent'] = function () { return Modernizr['generatedcontent'] }; tests['video'] = function () { var elem = document.createElement('video'), bool = false; try { if (bool = !!elem.canPlayType) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ''); bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ''); bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '') } } catch (e) { } return bool }; tests['audio'] = function () { var elem = document.createElement('audio'), bool = false; try { if (bool = !!elem.canPlayType) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''); bool.mp3 = elem.canPlayType('audio/mpeg;').replace(/^no$/, ''); bool.wav = elem.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''); bool.m4a = (elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')).replace(/^no$/, '') } } catch (e) { } return bool }; tests['localstorage'] = function () { try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true } catch (e) { return false } }; tests['sessionstorage'] = function () { try { sessionStorage.setItem(mod, mod); sessionStorage.removeItem(mod); return true } catch (e) { return false } }; tests['webworkers'] = function () { return !!window.Worker }; tests['applicationcache'] = function () { return !!window.applicationCache }; tests['svg'] = function () { return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect }; tests['inlinesvg'] = function () { var div = document.createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == ns.svg }; tests['smil'] = function () { return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))) }; tests['svgclippaths'] = function () { return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))) }; function webforms() { Modernizr['input'] = (function (props) { for (var i = 0, len = props.length; i < len; i++) { attrs[props[i]] = !!(props[i] in inputElem) } if (attrs.list) { attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement) } return attrs })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); Modernizr['inputtypes'] = (function (props) { for (var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++) { inputElem.setAttribute('type', inputElemType = props[i]); bool = inputElem.type !== 'text'; if (bool) { inputElem.value = smile; inputElem.style.cssText = 'position:absolute;visibility:hidden;'; if (/^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined) { docElement.appendChild(inputElem); defaultView = document.defaultView; bool = defaultView.getComputedStyle && defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && (inputElem.offsetHeight !== 0); docElement.removeChild(inputElem) } else if (/^(search|tel)$/.test(inputElemType)) { } else if (/^(url|email)$/.test(inputElemType)) { bool = inputElem.checkValidity && inputElem.checkValidity() === false } else if (/^color$/.test(inputElemType)) { docElement.appendChild(inputElem); docElement.offsetWidth; bool = inputElem.value != smile; docElement.removeChild(inputElem) } else { bool = inputElem.value != smile } } inputs[props[i]] = !!bool } return inputs })('search tel url email datetime date month week time datetime-local number range color'.split(' ')) } for (var feature in tests) { if (hasOwnProperty(tests, feature)) { featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName) } } Modernizr.input || webforms(); Modernizr.addTest = function (feature, test) { if (typeof feature == 'object') { for (var key in feature) { if (hasOwnProperty(feature, key)) { Modernizr.addTest(key, feature[key]) } } } else { feature = feature.toLowerCase(); if (Modernizr[feature] !== undefined) { return Modernizr } test = typeof test == 'function' ? test() : test; docElement.className += ' ' + (test ? '' : 'no-') + feature; Modernizr[feature] = test } return Modernizr }; setCss(''); modElem = inputElem = null; (function (window, document) { var options = window.html5 || {}; var reSkip = /^<|^(?:button|form|map|select|textarea)$/i; var supportsHtml5Styles; var supportsUnknownElements; (function () { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function () { try { (document.createElement)('a') } catch (e) { return true } var frag = document.createDocumentFragment(); return (typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined') } ()) } ()); function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild) } function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements } function shivMethods(ownerDocument) { var cache = {}, docCreateElement = ownerDocument.createElement, docCreateFragment = ownerDocument.createDocumentFragment, frag = docCreateFragment(); ownerDocument.createElement = function (nodeName) { var node = (cache[nodeName] || (cache[nodeName] = docCreateElement(nodeName))).cloneNode(); return html5.shivMethods && node.canHaveChildren && !reSkip.test(nodeName) ? frag.appendChild(node) : node }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + getElements().join().replace(/\w+/g, function (nodeName) { cache[nodeName] = docCreateElement(nodeName); frag.createElement(nodeName); return 'c("' + nodeName + '")' }) + ');return n}')(html5, frag) } function shivDocument(ownerDocument) { var shived; if (ownerDocument.documentShived) { return ownerDocument } if (html5.shivCSS && !supportsHtml5Styles) { shived = !!addStyleSheet(ownerDocument, 'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + 'audio{display:none}' + 'canvas,video{display:inline-block;*display:inline;*zoom:1}' + '[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}' + 'mark{background:#FF0;color:#000}') } if (!supportsUnknownElements) { shived = !shivMethods(ownerDocument) } if (shived) { ownerDocument.documentShived = shived } return ownerDocument } var html5 = { 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', 'shivCSS': !(options.shivCSS === false), 'shivMethods': !(options.shivMethods === false), 'type': 'default', 'shivDocument': shivDocument }; window.html5 = html5; shivDocument(document) } (this, document)); Modernizr._version = version; Modernizr._prefixes = prefixes; Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; Modernizr.mq = testMediaQuery; Modernizr.hasEvent = isEventSupported; Modernizr.testProp = function (prop) { return testProps([prop]) }; Modernizr.testAllProps = testPropsAll; Modernizr.testStyles = injectElementWithStyles; Modernizr.prefixed = function (prop, obj, elem) { if (!obj) { return testPropsAll(prop, 'pfx') } else { return testPropsAll(prop, obj, elem) } }; docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + (enableClasses ? ' js ' + classes.join(' ') : ''); return Modernizr })(this, this.document);
55 README.md
View
@@ -1,7 +1,56 @@
# modernizr-server-dotnet
-A library for accessing browser capabilities by [Modernizr](http://modernizr.com) on the server-side.
+A library for accessing browser capabilities by [Modernizr](http://modernizr.com) on the server.
-Loosely translated from James Pearce's [modernizr-server](https://github.com/jamesgpearce/modernizr-server) into .NET 4.0.
+Adapted from James Pearce's [modernizr-server](https://github.com/jamesgpearce/modernizr-server) into ASP.NET 4.0 with C# code-behind. Currently this is ASP.NET forms version. I plan on making an MVC version as well (see to-do's below).
-More coming soon!
+## How to Use
+For existing projects, include the server-side code on Default.aspx.cs in the Page_Load method of your default page. For new projects, you can simply copy Default.aspx and Default.aspx.cs and use that as a start to your default page.
+
+For new or existing projects, copy the ModernizrCookie.aspx and ModernizrCookie.aspx.cs files to your project. Also, grab the latest modernizr JS file from [Modernizr.com](http://modernizr.com) and include it in your project in the /js folder.
+
+In your web.config file, make sure to configure the session state if you have a particular preference on the session state mode. See [MSDN](msdn.microsoft.com/en-us/library/ms972429.aspx) for a brief overview of the session state configurations. I have the following (pretty close to default) configuration in the project:
+
+ <sessionState mode="InProc" cookieless="false" timeout="30" />
+
+This mode is the fastest, and uses a cookie to store the SessionId. I also have a sliding timeout of 30 minutes.
+
+After you have completed the above, on any page in your site, you can retrieve the Modernizr session object and store it in a dynamic variable like so:
+
+ dynamic Modernizr = Session["Modernizr"];
+
+You can see an example of this in VideoTest.aspx:
+
+ dynamic Modernizr = Session["Modernizr"];
+ if (Modernizr != null)
+ {
+ // Session object was succesfully retrieved and set
+ if (Modernizr.video != null)
+ {
+ // at least one video property is supported
+ if (Modernizr.video.h264)
+ {
+ // browser supports h.264
+ }
+ if (Modernizr.video.webm)
+ {
+ // browser supports webm
+ }
+ if (Modernizr.video.ogg)
+ {
+ // browser supports ogg
+ }
+ }
+ }
+
+## How it Works
+Much like the PHP implementation, the .NET version uses a combination of a cookie and the user's browsing session. The first time a user visits the site (specifically the default.aspx page), the server will redirect to a ModernizrCookie.aspx page, which is responsible for running the Modernizr JS and creating a serialized cookie that holds the browsers capabilities. This cookie is set to expire after 24 hours.
+
+After a cookie has been created (and on any new sessions for that particular user on that particular machine while the cookie is still valid) the server parses the cookie's data and places it in a dynamic object. The object is then stored in session and is available to any requests in that session.
+
+A bit of an improvement from the PHP version...If a cookie cannot be created the first time during a particular session, it will try again up to a set number of times. If it is still unsuccesful, the Modernizr capabilities will simply not be available to use. Therefore, it is important to always have a fallback in case the Modernizr session object is not available, or a particular
+
+## To-do's, etc.
+1. This is not compatible with earlier versions of .NET (3.5, 2.0, etc.). The dynamic object I am using was introduced in .NET 4.0
+2. Use with caution. I have not evaluated this for speed and efficiency in a production environment. This is merely for demonstration.
+3. I plan on making an MVC version of this so it can be used in MVC applications.

No commit comments for this range

Something went wrong with that request. Please try again.