Switching code – ASP.NET / C#
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Net" %>
<%
string mobileSite = "http://live.mobi";
string desktopSite = "http://google.com";
if(Request["redirect"]!=null && Request["redirect"]=="false") Response.Redirect(desktopSite);
string source = "none";
bool useCookies = true;
bool useCache = true;
string daJson = null;
string DA_CACHE_DIR = System.IO.Path.GetTempPath() + "DeviceAtlasCache\\";
string userAgent = Request.UserAgent.ToString();
if(useCookies) {
HttpCookie cookie = Request.Cookies["Mobi_Mtld_DA_Properties"];
if(cookie!=null) {
daJson = cookie.Value.ToString();
source = "cookie";
}
}
//Look up cache
if(useCache && source=="none") {
string filename = DA_CACHE_DIR + md5(userAgent) + ".json";
if(!Directory.Exists(DA_CACHE_DIR)) Directory.CreateDirectory(DA_CACHE_DIR);
else {
//Read the cache file if it exists (assumes just one line of text)
if(File.Exists(filename)) {
TextReader tr = new StreamReader(filename);
daJson = tr.ReadLine();
tr.Close();
source="cache";
}
}
}
//Look up DA webservice
if(source=="none") {
string url = "http://detect.deviceatlas.com/query?User-Agent=" + HttpUtility.UrlEncode(userAgent);
WebClient client = new WebClient();
daJson = client.DownloadString( url );
if(daJson!=null && daJson!="null") {
if(useCookies) {
HttpCookie cookie = new HttpCookie("Mobi_Mtld_DA_Properties");
cookie.Value = daJson;
Response.Cookies.Add(cookie);
}
if(useCache) {
string filename = DA_CACHE_DIR + md5(userAgent) + ".json";
TextWriter tw = new StreamWriter(filename);
tw.WriteLine(daJson);
tw.Close();
}
}
}
string isMobile = parseJson(daJson, "mobileDevice");
if(isMobile=="true") Response.Redirect(mobileSite);
else Response.Redirect(desktopSite);
%>
//Parse json for property - really basic & assumes flat json file as returned by DA service
string parseJson(String json, String property) {
string[] tokens = Regex.Split(json, ",\\s\"|\":|\\{\"|:\\s|,\\s|\\}");
for(int i=0;i