diff --git a/Disco.BI/BI/Interop/Community/UpdateCheck.cs b/Disco.BI/BI/Interop/Community/UpdateCheck.cs index ce76b880..6da4bd12 100644 --- a/Disco.BI/BI/Interop/Community/UpdateCheck.cs +++ b/Disco.BI/BI/Interop/Community/UpdateCheck.cs @@ -1,185 +1,198 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Linq; -using System.Xml.Serialization; -using Disco.Data.Repository; -using Disco.Models.BI.Interop.Community; -using Disco.Services.Tasks; -using Newtonsoft.Json; - -namespace Disco.BI.Interop.Community -{ - public static class UpdateCheck - { - private static string UpdateUrl(DiscoDataContext db) - { - // Special case for DiscoCommunity Hosting Network - try - { - var ip = (from addr in Dns.GetHostEntry(Dns.GetHostName()).AddressList - where addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork - && addr.ToString().StartsWith("10.131.200.") - select addr).FirstOrDefault(); - if (ip != null) - { - return "http://hades3:9393/base/DiscoUpdate/V1"; - } - } - catch (Exception) - {} // Ignore Errors - - return "http://discoict.com.au/base/DiscoUpdate/V1"; - } - - public static string CurrentDiscoVersion() - { - var AssemblyVersion = typeof(UpdateCheck).Assembly.GetName().Version; - return string.Format("{0}.{1}.{2:0000}.{3:0000}", AssemblyVersion.Major, AssemblyVersion.Minor, AssemblyVersion.Build, AssemblyVersion.Revision); - } - - public static UpdateResponse Check(DiscoDataContext db, bool UseProxy, ScheduledTaskStatus status = null) - { - if (status != null) - status.UpdateStatus(10, "Building Update Request"); - - var request = BuildRequest(db); - //var requestJson = JsonConvert.SerializeObject(request); - - if (status != null) - status.UpdateStatus(40, "Sending Request"); - - var DiscoBIVersion = CurrentDiscoVersion(); - - HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateUrl(db)); - webRequest.ContentType = "application/json"; - webRequest.Method = WebRequestMethods.Http.Post; - webRequest.UserAgent = string.Format("Disco/{0} (Update)", DiscoBIVersion); - - using (var wrStream = webRequest.GetRequestStream()) - { - XmlSerializer xml = new XmlSerializer(typeof(UpdateRequestV1)); - xml.Serialize(wrStream, request); - } - if (status != null) - status.UpdateStatus(50, "Waiting for Response"); - using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) - { - if (webResponse.StatusCode == HttpStatusCode.OK) - { - if (status != null) - status.UpdateStatus(90, "Reading Response"); - UpdateResponse result; - using (var wResStream = webResponse.GetResponseStream()) - { - XmlSerializer xml = new XmlSerializer(typeof(UpdateResponse)); - result = (UpdateResponse)xml.Deserialize(wResStream); - } - //var result = JsonConvert.DeserializeObject(responseContent); - db.DiscoConfiguration.UpdateLastCheck = result; - db.SaveChanges(); - - status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", result.Version)); - - return result; - } - else - { - if (status != null) - status.SetTaskException(new WebException(string.Format("Server responded with: [{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription))); - return null; - } - } - } - - private static UpdateRequestV1 BuildRequest(DiscoDataContext db) - { - var m = new UpdateRequestV1(); - - m.DeploymentId = db.DiscoConfiguration.DeploymentId; - - m.CurrentDiscoVersion = CurrentDiscoVersion(); - - m.OrganisationName = db.DiscoConfiguration.OrganisationName; - m.BroadbandDoeWanId = GetBroadbandDoeWanId(); - m.BetaDeployment = db.DiscoConfiguration.UpdateBetaDeployment; - - m.Stat_JobCounts = db.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); - m.Stat_OpenJobCounts = db.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); - var activeThreshold = DateTime.Now.AddDays(-60); - m.Stat_ActiveDeviceModelCounts = db.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList(); - m.Stat_UserCounts = db.Users.GroupBy(u => u.Type).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); - - return m; - } - - #region DoE Query - public static string GetBroadbandDoeWanId() - { - // DnsQuery for broadband.doe.wan - IPHostEntry doeWanDnsEntry; - try - { - doeWanDnsEntry = Dns.GetHostEntry("broadband.doe.wan"); - } - catch (Exception) - { return null; } // Fail on error - - // Try using IPSearch feature - XDocument doeWanIPSearchResult = TryDownloadDoeIPSearch(false); - if (doeWanIPSearchResult == null) - doeWanIPSearchResult = TryDownloadDoeIPSearch(true); - - if (doeWanIPSearchResult == null) - return null; - - try - { - return doeWanIPSearchResult.Element("resultset").Element("site").Element("number").Value.ToLower(); - } - catch (Exception) - { return null; } // Fail on error - } - private static XDocument TryDownloadDoeIPSearch(bool useProxy) - { - try - { - var DiscoBIVersion = CurrentDiscoVersion(); - - HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://broadband.doe.wan/ipsearch/showresult.php"); - if (!useProxy) - wReq.Proxy = new WebProxy(); // Empty Proxy Config - wReq.Method = WebRequestMethods.Http.Post; - wReq.ContentType = "application/x-www-form-urlencoded"; - wReq.UserAgent = string.Format("Disco/{0}", DiscoBIVersion); - using (var wrStream = wReq.GetRequestStream()) - { - using (var wrStreamWriter = new StreamWriter(wrStream)) - { - wrStreamWriter.Write("mode=whoami"); - } - } - using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) - { - if (wRes.StatusCode == HttpStatusCode.OK) - { - using (var wResStream = wRes.GetResponseStream()) - { - return XDocument.Load(wResStream); - } - } - else - return null; - } - } - catch (Exception) - { return null; } // Fail on error - } - #endregion - - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; +using System.Xml.Serialization; +using Disco.Data.Repository; +using Disco.Models.BI.Interop.Community; +using Disco.Services.Tasks; +using Newtonsoft.Json; + +namespace Disco.BI.Interop.Community +{ + public static class UpdateCheck + { + private static string UpdateUrl(DiscoDataContext db) + { + // Special case for DiscoCommunity Hosting Network + try + { + var ip = (from addr in Dns.GetHostEntry(Dns.GetHostName()).AddressList + where addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork + && addr.ToString().StartsWith("10.131.200.") + select addr).FirstOrDefault(); + if (ip != null) + { + return "http://hades3:9393/base/DiscoUpdate/V1"; + } + } + catch (Exception) + { } // Ignore Errors + + return "http://discoict.com.au/base/DiscoUpdate/V1"; + } + + public static string CurrentDiscoVersion() + { + var AssemblyVersion = typeof(UpdateCheck).Assembly.GetName().Version; + return string.Format("{0}.{1}.{2:0000}.{3:0000}", AssemblyVersion.Major, AssemblyVersion.Minor, AssemblyVersion.Build, AssemblyVersion.Revision); + } + + public static UpdateResponse Check(DiscoDataContext db, bool UseProxy, ScheduledTaskStatus status = null) + { + if (status != null) + status.UpdateStatus(10, "Building Update Request"); + + var request = BuildRequest(db); + //var requestJson = JsonConvert.SerializeObject(request); + + if (status != null) + status.UpdateStatus(40, "Sending Request"); + + var DiscoBIVersion = CurrentDiscoVersion(); + + HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateUrl(db)); + + // Added: 2013-02-08 G# + // Fix for Proxy Servers which dont support KeepAlive + webRequest.KeepAlive = false; + // End Added: 2013-02-08 G# + + if (!UseProxy) + webRequest.Proxy = new WebProxy(); + + webRequest.ContentType = "application/json"; + webRequest.Method = WebRequestMethods.Http.Post; + webRequest.UserAgent = string.Format("Disco/{0} (Update)", DiscoBIVersion); + + using (var wrStream = webRequest.GetRequestStream()) + { + XmlSerializer xml = new XmlSerializer(typeof(UpdateRequestV1)); + xml.Serialize(wrStream, request); + } + if (status != null) + status.UpdateStatus(50, "Waiting for Response"); + using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) + { + if (webResponse.StatusCode == HttpStatusCode.OK) + { + if (status != null) + status.UpdateStatus(90, "Reading Response"); + UpdateResponse result; + using (var wResStream = webResponse.GetResponseStream()) + { + XmlSerializer xml = new XmlSerializer(typeof(UpdateResponse)); + result = (UpdateResponse)xml.Deserialize(wResStream); + } + //var result = JsonConvert.DeserializeObject(responseContent); + db.DiscoConfiguration.UpdateLastCheck = result; + db.SaveChanges(); + + status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", result.Version)); + + return result; + } + else + { + if (status != null) + status.SetTaskException(new WebException(string.Format("Server responded with: [{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription))); + return null; + } + } + } + + private static UpdateRequestV1 BuildRequest(DiscoDataContext db) + { + var m = new UpdateRequestV1(); + + m.DeploymentId = db.DiscoConfiguration.DeploymentId; + + m.CurrentDiscoVersion = CurrentDiscoVersion(); + + m.OrganisationName = db.DiscoConfiguration.OrganisationName; + m.BroadbandDoeWanId = GetBroadbandDoeWanId(); + m.BetaDeployment = db.DiscoConfiguration.UpdateBetaDeployment; + + m.Stat_JobCounts = db.Jobs.GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + m.Stat_OpenJobCounts = db.Jobs.Where(j => j.ClosedDate == null).GroupBy(j => j.JobTypeId).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + var activeThreshold = DateTime.Now.AddDays(-60); + m.Stat_ActiveDeviceModelCounts = db.DeviceModels.Select(dm => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = dm.Manufacturer + ";" + dm.Model, Count = dm.Devices.Count(d => d.DecommissionedDate == null && (d.LastNetworkLogonDate == null || d.LastNetworkLogonDate > activeThreshold)) }).ToList(); + m.Stat_UserCounts = db.Users.GroupBy(u => u.Type).Select(g => new Disco.Models.BI.Interop.Community.UpdateRequestV1.Stat { Key = g.Key, Count = g.Count() }).ToList(); + + return m; + } + + #region DoE Query + public static string GetBroadbandDoeWanId() + { + // DnsQuery for broadband.doe.wan + IPHostEntry doeWanDnsEntry; + try + { + doeWanDnsEntry = Dns.GetHostEntry("broadband.doe.wan"); + } + catch (Exception) + { return null; } // Fail on error + + // Try using IPSearch feature + XDocument doeWanIPSearchResult = TryDownloadDoeIPSearch(false); + if (doeWanIPSearchResult == null) + doeWanIPSearchResult = TryDownloadDoeIPSearch(true); + + if (doeWanIPSearchResult == null) + return null; + + try + { + return doeWanIPSearchResult.Element("resultset").Element("site").Element("number").Value.ToLower(); + } + catch (Exception) + { return null; } // Fail on error + } + private static XDocument TryDownloadDoeIPSearch(bool useProxy) + { + try + { + var DiscoBIVersion = CurrentDiscoVersion(); + + HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://broadband.doe.wan/ipsearch/showresult.php"); + // Added: 2013-02-08 G# + // Fix for Proxy Servers which dont support KeepAlive + webRequest.KeepAlive = false; + // End Added: 2013-02-08 G# + if (!useProxy) + wReq.Proxy = new WebProxy(); // Empty Proxy Config + wReq.Method = WebRequestMethods.Http.Post; + wReq.ContentType = "application/x-www-form-urlencoded"; + wReq.UserAgent = string.Format("Disco/{0}", DiscoBIVersion); + using (var wrStream = wReq.GetRequestStream()) + { + using (var wrStreamWriter = new StreamWriter(wrStream)) + { + wrStreamWriter.Write("mode=whoami"); + } + } + using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) + { + if (wRes.StatusCode == HttpStatusCode.OK) + { + using (var wResStream = wRes.GetResponseStream()) + { + return XDocument.Load(wResStream); + } + } + else + return null; + } + } + catch (Exception) + { return null; } // Fail on error + } + #endregion + + } +} diff --git a/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs b/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs index 9cfbca9c..c09dfa28 100644 --- a/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs +++ b/Disco.BI/BI/Interop/Community/UpdateCheckTask.cs @@ -1,86 +1,87 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Disco.Data.Repository; -using Disco.Services.Logging; -using Disco.Services.Tasks; -using Quartz; - -namespace Disco.BI.Interop.Community -{ - public class UpdateCheckTask : ScheduledTask - { - public override string TaskName { get { return "Disco Community - Check for Update"; } } - public override bool SingleInstanceTask { get { return true; } } - public override bool CancelInitiallySupported { get { return false; } } - - public static ScheduledTaskStatus ScheduleNow() - { - - var runningTasks = ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).Where(ts => ts.IsRunning).ToList(); - if (runningTasks.Count > 0) - return runningTasks.First(); - else - { - var t = new UpdateCheckTask(); - return t.ScheduleTask(); - } - } - public static ScheduledTaskStatus RunningStatus - { - get - { - return ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).Where(ts => ts.IsRunning).FirstOrDefault(); - } - } - public static DateTime? NextScheduled - { - get - { - var runningTasks = ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).ToList(); - DateTime timestamp = DateTime.MaxValue; - foreach (var t in runningTasks) - { - if (t.NextScheduledTimestamp != null && t.NextScheduledTimestamp.Value < timestamp) - timestamp = t.NextScheduledTimestamp.Value; - } - if (timestamp == DateTime.MaxValue) - return null; - else - return timestamp; - } - } - - public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext dbContext) - { - // ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm - var rnd = new Random(); - - var rndHour = rnd.Next(12, 23); - var rndMinute = rnd.Next(0, 59); - - TriggerBuilder triggerBuilder = TriggerBuilder.Create(). - WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(rndHour, rndMinute)); - - this.ScheduleTask(triggerBuilder); - } - - protected override void ExecuteTask() - { - using (DiscoDataContext db = new DiscoDataContext()) - { - try - { - UpdateCheck.Check(db, true, this.Status); - } - catch (Exception) - { - // Could be proxy error - try again without proxy: - UpdateCheck.Check(db, false, this.Status); - } - } - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Disco.Data.Repository; +using Disco.Services.Logging; +using Disco.Services.Tasks; +using Quartz; + +namespace Disco.BI.Interop.Community +{ + public class UpdateCheckTask : ScheduledTask + { + public override string TaskName { get { return "Disco Community - Check for Update"; } } + public override bool SingleInstanceTask { get { return true; } } + public override bool CancelInitiallySupported { get { return false; } } + + public static ScheduledTaskStatus ScheduleNow() + { + + var runningTasks = ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).Where(ts => ts.IsRunning).ToList(); + if (runningTasks.Count > 0) + return runningTasks.First(); + else + { + var t = new UpdateCheckTask(); + return t.ScheduleTask(); + } + } + public static ScheduledTaskStatus RunningStatus + { + get + { + return ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).Where(ts => ts.IsRunning).FirstOrDefault(); + } + } + public static DateTime? NextScheduled + { + get + { + var runningTasks = ScheduledTasks.GetTaskStatuses(typeof(UpdateCheckTask)).ToList(); + DateTime timestamp = DateTime.MaxValue; + foreach (var t in runningTasks) + { + if (t.NextScheduledTimestamp != null && t.NextScheduledTimestamp.Value < timestamp) + timestamp = t.NextScheduledTimestamp.Value; + } + if (timestamp == DateTime.MaxValue) + return null; + else + return timestamp; + } + } + + public override void InitalizeScheduledTask(Data.Repository.DiscoDataContext dbContext) + { + // ActiveDirectoryUpdateLastNetworkLogonDateJob @ 11:30pm + var rnd = new Random(); + + var rndHour = rnd.Next(12, 23); + var rndMinute = rnd.Next(0, 59); + + TriggerBuilder triggerBuilder = TriggerBuilder.Create(). + WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(rndHour, rndMinute)); + + this.ScheduleTask(triggerBuilder); + } + + protected override void ExecuteTask() + { + using (DiscoDataContext db = new DiscoDataContext()) + { + try + { + UpdateCheck.Check(db, true, this.Status); + } + catch (Exception ex) + { + ScheduledTasksLog.LogScheduledTaskException(this.Status.TaskName, this.Status.SessionId, this.Status.TaskType, ex); + // Could be proxy error - try again without proxy: + UpdateCheck.Check(db, false, this.Status); + } + } + } + } +} diff --git a/Disco.BI/Properties/AssemblyInfo.cs b/Disco.BI/Properties/AssemblyInfo.cs index 4da37026..cb24ca64 100644 --- a/Disco.BI/Properties/AssemblyInfo.cs +++ b/Disco.BI/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.2.0207.1853")] -[assembly: AssemblyFileVersion("1.2.0207.1853")] +[assembly: AssemblyVersion("1.2.0208.1156")] +[assembly: AssemblyFileVersion("1.2.0208.1156")] diff --git a/Disco.Web/Global.asax.cs b/Disco.Web/Global.asax.cs index 5063f4d6..41ca9cab 100644 --- a/Disco.Web/Global.asax.cs +++ b/Disco.Web/Global.asax.cs @@ -1,205 +1,212 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Security.Principal; -using System.Web; -using System.Web.Http; -using System.Web.Mvc; -using System.Web.Routing; -using Disco.Data.Repository; -using Disco.Models.Repository; - -namespace Disco.Web -{ - // Note: For instructions on enabling IIS6 or IIS7 classic mode, - // visit http://go.microsoft.com/?LinkId=9394801 - - public class DiscoApplication : System.Web.HttpApplication - { - public DiscoApplication() - { - base.AuthenticateRequest += new EventHandler(DiscoApplication_AuthenticateRequest); - base.BeginRequest += new EventHandler(DiscoApplication_BeginRequest); - base.Error += new EventHandler(DiscoApplication_Error); - } - - protected void Application_Start() - { - var timer = new Stopwatch(); - long timer_last; - timer.Start(); - - - Debug.WriteLine("Application Startup Profiling Started"); - timer_last = timer.ElapsedMilliseconds; - - if (AppConfig.InitializeDatabase()) - { - Debug.WriteLine("Initialized Database: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - AreaRegistration.RegisterAllAreas(); - - Debug.WriteLine("Registered Areas: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - WebApiConfig.Register(GlobalConfiguration.Configuration); - - Debug.WriteLine("Registered API: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); - - Debug.WriteLine("Registered Global Filters: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - RouteConfig.RegisterRoutes(RouteTable.Routes); - - Debug.WriteLine("Registered Routes: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - BundleConfig.RegisterBundles(); - - Debug.WriteLine("Registered Bundles: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - - AppConfig.InitalizeEnvironment(); - - Debug.WriteLine("Initialized Environment: +{0}ms", timer.ElapsedMilliseconds - timer_last); - timer_last = timer.ElapsedMilliseconds; - } - else - { - // Install - InitialConfig = true; - RouteConfig.RegisterInstallRoutes(RouteTable.Routes); - BundleConfig.RegisterBundles(); - } - } - protected void Application_End() - { - AppConfig.DisposeEnvironment(); - } - - void DiscoApplication_BeginRequest(object sender, EventArgs e) - { - // Force Disable IE Compatibility Mode - Response.Headers.Add("X-UA-Compatible", "IE=edge"); - } - - #region Authentication - void DiscoApplication_AuthenticateRequest(object sender, EventArgs e) - { - User u = CurrentUser; - if (u != null) - { - base.Context.User = new GenericPrincipal(base.Context.User.Identity, new string[] { u.Type }); - } - } - - public static bool InitialConfig { get; set; } - - public static User CurrentUser - { - get - { - if (!InitialConfig) - return BI.UserBI.UserCache.CurrentUser; - else - return null; - } - } - #endregion - #region Cached Properties - - private static string _OrganisationName; - public static string OrganisationName - { - get - { - if (string.IsNullOrWhiteSpace(_OrganisationName)) - { - return "Unknown"; - } - return _OrganisationName; - } - set - { - _OrganisationName = value; - } - } - public static bool MultiSiteMode { get; set; } - - #region Version - private static Lazy _Version = new Lazy(() => - { - var AssemblyVersion = typeof(DiscoApplication).Assembly.GetName().Version; - return string.Format("{0}.{1}.{2:0000}", AssemblyVersion.Major, AssemblyVersion.Minor, AssemblyVersion.Build); - }); - public static string Version - { - get - { - return _Version.Value; - } - } - #endregion - - #endregion - #region Proxy - private static IWebProxy _defaultProxy; - public static void SetGlobalProxy(string Address, int Port, string Username, string Password) - { - if (_defaultProxy == null) - { - _defaultProxy = WebRequest.DefaultWebProxy; - } - if (!string.IsNullOrWhiteSpace(Address)) - { - WebProxy p = new WebProxy(new Uri(string.Format("http://{0}:{1}", Address, Port))); - if (!string.IsNullOrWhiteSpace(Username)) - { - p.Credentials = new NetworkCredential(Username, Password); - } - WebRequest.DefaultWebProxy = p; - } - else - { - WebRequest.DefaultWebProxy = _defaultProxy; - } - } - #endregion - #region Scheduler Factory - private static Lazy _SchedulerFactory = new Lazy(() => - { - // Initialize Scheduler Factory - return new Quartz.Impl.StdSchedulerFactory(); - }); - public static Quartz.ISchedulerFactory SchedulerFactory - { - get - { - return _SchedulerFactory.Value; - } - } - #endregion - #region Dropbox Monitor - public static BI.DocumentTemplateBI.Importer.DocumentDropBoxMonitor DocumentDropBoxMonitor { get; set; } - #endregion - #region Global Error Logging - void DiscoApplication_Error(object sender, EventArgs e) - { - try - { - Disco.Services.Logging.SystemLog.LogException("Global Application Exception Caught", Server.GetLastError()); - } - catch (Exception) - { - // Ignore all logging errors - } - } - #endregion - } +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Security.Principal; +using System.Web; +using System.Web.Http; +using System.Web.Mvc; +using System.Web.Routing; +using Disco.Data.Repository; +using Disco.Models.Repository; + +namespace Disco.Web +{ + // Note: For instructions on enabling IIS6 or IIS7 classic mode, + // visit http://go.microsoft.com/?LinkId=9394801 + + public class DiscoApplication : System.Web.HttpApplication + { + public DiscoApplication() + { + base.AuthenticateRequest += new EventHandler(DiscoApplication_AuthenticateRequest); + base.BeginRequest += new EventHandler(DiscoApplication_BeginRequest); + base.Error += new EventHandler(DiscoApplication_Error); + } + + protected void Application_Start() + { + var timer = new Stopwatch(); + long timer_last; + timer.Start(); + + + Debug.WriteLine("Application Startup Profiling Started"); + timer_last = timer.ElapsedMilliseconds; + + if (AppConfig.InitializeDatabase()) + { + Debug.WriteLine("Initialized Database: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + AreaRegistration.RegisterAllAreas(); + + Debug.WriteLine("Registered Areas: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + WebApiConfig.Register(GlobalConfiguration.Configuration); + + Debug.WriteLine("Registered API: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + + Debug.WriteLine("Registered Global Filters: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + RouteConfig.RegisterRoutes(RouteTable.Routes); + + Debug.WriteLine("Registered Routes: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + BundleConfig.RegisterBundles(); + + Debug.WriteLine("Registered Bundles: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + + AppConfig.InitalizeEnvironment(); + + Debug.WriteLine("Initialized Environment: +{0}ms", timer.ElapsedMilliseconds - timer_last); + timer_last = timer.ElapsedMilliseconds; + } + else + { + // Install + InitialConfig = true; + RouteConfig.RegisterInstallRoutes(RouteTable.Routes); + BundleConfig.RegisterBundles(); + } + } + protected void Application_End() + { + AppConfig.DisposeEnvironment(); + } + + void DiscoApplication_BeginRequest(object sender, EventArgs e) + { + // Force Disable IE Compatibility Mode + Response.Headers.Add("X-UA-Compatible", "IE=edge"); + } + + #region Authentication + void DiscoApplication_AuthenticateRequest(object sender, EventArgs e) + { + User u = CurrentUser; + if (u != null) + { + base.Context.User = new GenericPrincipal(base.Context.User.Identity, new string[] { u.Type }); + } + } + + public static bool InitialConfig { get; set; } + + public static User CurrentUser + { + get + { + if (!InitialConfig) + return BI.UserBI.UserCache.CurrentUser; + else + return null; + } + } + #endregion + #region Cached Properties + + private static string _OrganisationName; + public static string OrganisationName + { + get + { + if (string.IsNullOrWhiteSpace(_OrganisationName)) + { + return "Unknown"; + } + return _OrganisationName; + } + set + { + _OrganisationName = value; + } + } + public static bool MultiSiteMode { get; set; } + + #region Version + private static Lazy _Version = new Lazy(() => + { + var AssemblyVersion = typeof(DiscoApplication).Assembly.GetName().Version; + return string.Format("{0}.{1}.{2:0000}", AssemblyVersion.Major, AssemblyVersion.Minor, AssemblyVersion.Build); + }); + public static string Version + { + get + { + return _Version.Value; + } + } + #endregion + + #endregion + #region Proxy + private static IWebProxy _defaultProxy; + public static void SetGlobalProxy(string Address, int Port, string Username, string Password) + { + if (_defaultProxy == null) + { + _defaultProxy = WebRequest.DefaultWebProxy; + } + if (!string.IsNullOrWhiteSpace(Address)) + { + WebProxy p = new WebProxy(Address, Port); + p.BypassProxyOnLocal = true; + if (!string.IsNullOrWhiteSpace(Username)) + { + p.Credentials = new NetworkCredential(Username, Password); + } + else + { + // Added 2013-02-08 G# + // Improve support for Integrated Windows Authentication + p.UseDefaultCredentials = true; + } + WebRequest.DefaultWebProxy = p; + } + else + { + WebRequest.DefaultWebProxy = _defaultProxy; + } + } + #endregion + #region Scheduler Factory + private static Lazy _SchedulerFactory = new Lazy(() => + { + // Initialize Scheduler Factory + return new Quartz.Impl.StdSchedulerFactory(); + }); + public static Quartz.ISchedulerFactory SchedulerFactory + { + get + { + return _SchedulerFactory.Value; + } + } + #endregion + #region Dropbox Monitor + public static BI.DocumentTemplateBI.Importer.DocumentDropBoxMonitor DocumentDropBoxMonitor { get; set; } + #endregion + #region Global Error Logging + void DiscoApplication_Error(object sender, EventArgs e) + { + try + { + Disco.Services.Logging.SystemLog.LogException("Global Application Exception Caught", Server.GetLastError()); + } + catch (Exception) + { + // Ignore all logging errors + } + } + #endregion + } } \ No newline at end of file diff --git a/Disco.Web/Models/InitialConfig/CompleteModel.cs b/Disco.Web/Models/InitialConfig/CompleteModel.cs index 2e52f103..f1fa4881 100644 --- a/Disco.Web/Models/InitialConfig/CompleteModel.cs +++ b/Disco.Web/Models/InitialConfig/CompleteModel.cs @@ -1,88 +1,92 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Net; -using System.IO; - -namespace Disco.Web.Models.InitialConfig -{ - public class CompleteModel - { - public Tuple DiscoDnsTestResult { get; set; } - public Exception RegistryDatabaseResult { get; set; } - public Exception DiscoIctComAuWebResult { get; set; } - - public bool LaunchAllowed - { - get - { - return (RegistryDatabaseResult == null); - } - } - - public void PerformTests() - { - - #region DNS for 'Disco' - try - { - // Try and Resolve 'disco' - DiscoDnsTestResult = new Tuple(Dns.GetHostEntry("disco"), null); - } - catch (Exception ex) - { - DiscoDnsTestResult = new Tuple(null, ex); - } - #endregion - - #region Write Database to Registry - try - { - // Make Connection String Persistent - Disco.Data.Repository.DiscoDatabaseConnectionFactory.SetDiscoDataContextConnectionString( - Disco.Data.Repository.DiscoDatabaseConnectionFactory.DiscoDataContextConnectionString, true); - RegistryDatabaseResult = null; - } - catch (Exception ex) - { - RegistryDatabaseResult = ex; - } - #endregion - - #region Communicate with http://discoict.com.au/ - try - { - Dns.GetHostEntry("discoict.com.au"); - try - { - HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://discoict.com.au/"); - wReq.Method = WebRequestMethods.Http.Get; - wReq.UserAgent = string.Format("Disco/{0} (Initial Config; Org: {1})", DiscoApplication.Version, DiscoApplication.OrganisationName); - using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) - { - if (wRes.StatusCode == HttpStatusCode.OK) - { - DiscoIctComAuWebResult = null; - } - else - { - DiscoIctComAuWebResult = new Exception(string.Format("Server returned response: [{0}] {1}", wRes.StatusCode, wRes.StatusDescription)); - } - } - } - catch (Exception ex) - { - DiscoIctComAuWebResult = new WebException("DNS Resolved the host 'discoict.com.au' but could not establish a connection.", ex); - } - } - catch (Exception ex) - { - DiscoIctComAuWebResult = new Exception("Could not resolve the name 'discoict.com.au'", ex); - throw; - } - #endregion - - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Net; +using System.IO; + +namespace Disco.Web.Models.InitialConfig +{ + public class CompleteModel + { + public Tuple DiscoDnsTestResult { get; set; } + public Exception RegistryDatabaseResult { get; set; } + public Exception DiscoIctComAuWebResult { get; set; } + + public bool LaunchAllowed + { + get + { + return (RegistryDatabaseResult == null); + } + } + + public void PerformTests() + { + + #region DNS for 'Disco' + try + { + // Try and Resolve 'disco' + DiscoDnsTestResult = new Tuple(Dns.GetHostEntry("disco"), null); + } + catch (Exception ex) + { + DiscoDnsTestResult = new Tuple(null, ex); + } + #endregion + + #region Write Database to Registry + try + { + // Make Connection String Persistent + Disco.Data.Repository.DiscoDatabaseConnectionFactory.SetDiscoDataContextConnectionString( + Disco.Data.Repository.DiscoDatabaseConnectionFactory.DiscoDataContextConnectionString, true); + RegistryDatabaseResult = null; + } + catch (Exception ex) + { + RegistryDatabaseResult = ex; + } + #endregion + + #region Communicate with http://discoict.com.au/ + try + { + Dns.GetHostEntry("discoict.com.au"); + try + { + HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://discoict.com.au/"); + // Added: 2013-02-08 G# + // Fix for Proxy Servers which dont support KeepAlive + wReq.KeepAlive = false; + // End Added: 2013-02-08 G# + wReq.Method = WebRequestMethods.Http.Get; + wReq.UserAgent = string.Format("Disco/{0} (Initial Config; Org: {1})", DiscoApplication.Version, DiscoApplication.OrganisationName); + using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) + { + if (wRes.StatusCode == HttpStatusCode.OK) + { + DiscoIctComAuWebResult = null; + } + else + { + DiscoIctComAuWebResult = new Exception(string.Format("Server returned response: [{0}] {1}", wRes.StatusCode, wRes.StatusDescription)); + } + } + } + catch (Exception ex) + { + DiscoIctComAuWebResult = new WebException("DNS Resolved the host 'discoict.com.au' but could not establish a connection.", ex); + } + } + catch (Exception ex) + { + DiscoIctComAuWebResult = new Exception("Could not resolve the name 'discoict.com.au'", ex); + throw; + } + #endregion + + } + } } \ No newline at end of file diff --git a/Disco.Web/Models/InitialConfig/WelcomeModel.cs b/Disco.Web/Models/InitialConfig/WelcomeModel.cs index 2c0b4339..410b0128 100644 --- a/Disco.Web/Models/InitialConfig/WelcomeModel.cs +++ b/Disco.Web/Models/InitialConfig/WelcomeModel.cs @@ -1,90 +1,94 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -using System.Net; -using System.Xml.Linq; -using System.IO; -using System.Globalization; - -namespace Disco.Web.Models.InitialConfig -{ - public class WelcomeModel - { - [Required(ErrorMessage="The Organisation Name is required.")] - public string OrganisationName { get; set; } - - - private static string _OrganisationNameCache; - public bool AutodetectOrganisation() - { - if (_OrganisationNameCache != null) - { - this.OrganisationName = _OrganisationNameCache; - return true; - } - - // DnsQuery for broadband.doe.wan - IPHostEntry doeWanDnsEntry; - try - { - doeWanDnsEntry = Dns.GetHostEntry("broadband.doe.wan"); - } - catch (Exception) - { return false; } // Fail on error - - // Try using IPSearch feature - XDocument doeWanIPSearchResult = TryDownloadDoeIPSearch(true); - if (doeWanIPSearchResult == null) - doeWanIPSearchResult = TryDownloadDoeIPSearch(false); - - if (doeWanIPSearchResult == null) - return false; - - try - { - var siteName = doeWanIPSearchResult.Element("resultset").Element("site").Element("name").Value.ToLower(); - this.OrganisationName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(siteName); - _OrganisationNameCache = this.OrganisationName; - return true; - } - catch (Exception) - { return false; } // Fail on error - } - private XDocument TryDownloadDoeIPSearch(bool useProxy) - { - try - { - HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://broadband.doe.wan/ipsearch/showresult.php"); - if (!useProxy) - wReq.Proxy = new WebProxy(); // Empty Proxy Config - wReq.Method = WebRequestMethods.Http.Post; - wReq.ContentType = "application/x-www-form-urlencoded"; - wReq.UserAgent = string.Format("Disco/{0}", DiscoApplication.Version); - using (var wrStream = wReq.GetRequestStream()) - { - using (var wrStreamWriter = new StreamWriter(wrStream)) - { - wrStreamWriter.Write("mode=whoami"); - } - } - using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) - { - if (wRes.StatusCode == HttpStatusCode.OK) - { - using (var wResStream = wRes.GetResponseStream()) - { - return XDocument.Load(wResStream); - } - } - else - return null; - } - } - catch (Exception) - { return null; } // Fail on error - } - - } +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Web; +using System.Net; +using System.Xml.Linq; +using System.IO; +using System.Globalization; + +namespace Disco.Web.Models.InitialConfig +{ + public class WelcomeModel + { + [Required(ErrorMessage="The Organisation Name is required.")] + public string OrganisationName { get; set; } + + + private static string _OrganisationNameCache; + public bool AutodetectOrganisation() + { + if (_OrganisationNameCache != null) + { + this.OrganisationName = _OrganisationNameCache; + return true; + } + + // DnsQuery for broadband.doe.wan + IPHostEntry doeWanDnsEntry; + try + { + doeWanDnsEntry = Dns.GetHostEntry("broadband.doe.wan"); + } + catch (Exception) + { return false; } // Fail on error + + // Try using IPSearch feature + XDocument doeWanIPSearchResult = TryDownloadDoeIPSearch(true); + if (doeWanIPSearchResult == null) + doeWanIPSearchResult = TryDownloadDoeIPSearch(false); + + if (doeWanIPSearchResult == null) + return false; + + try + { + var siteName = doeWanIPSearchResult.Element("resultset").Element("site").Element("name").Value.ToLower(); + this.OrganisationName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(siteName); + _OrganisationNameCache = this.OrganisationName; + return true; + } + catch (Exception) + { return false; } // Fail on error + } + private XDocument TryDownloadDoeIPSearch(bool useProxy) + { + try + { + HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("http://broadband.doe.wan/ipsearch/showresult.php"); + // Added: 2013-02-08 G# + // Fix for Proxy Servers which dont support KeepAlive + wReq.KeepAlive = false; + // End Added: 2013-02-08 G# + if (!useProxy) + wReq.Proxy = new WebProxy(); // Empty Proxy Config + wReq.Method = WebRequestMethods.Http.Post; + wReq.ContentType = "application/x-www-form-urlencoded"; + wReq.UserAgent = string.Format("Disco/{0}", DiscoApplication.Version); + using (var wrStream = wReq.GetRequestStream()) + { + using (var wrStreamWriter = new StreamWriter(wrStream)) + { + wrStreamWriter.Write("mode=whoami"); + } + } + using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) + { + if (wRes.StatusCode == HttpStatusCode.OK) + { + using (var wResStream = wRes.GetResponseStream()) + { + return XDocument.Load(wResStream); + } + } + else + return null; + } + } + catch (Exception) + { return null; } // Fail on error + } + + } } \ No newline at end of file diff --git a/Disco.Web/Properties/AssemblyInfo.cs b/Disco.Web/Properties/AssemblyInfo.cs index 267c7ac7..e1135f98 100644 --- a/Disco.Web/Properties/AssemblyInfo.cs +++ b/Disco.Web/Properties/AssemblyInfo.cs @@ -31,5 +31,5 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.2.0207.1727")] -[assembly: AssemblyFileVersion("1.2.0207.1727")] +[assembly: AssemblyVersion("1.2.0208.1156")] +[assembly: AssemblyFileVersion("1.2.0208.1156")]