PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/Code/Client/Inbox2/Core/Startup.cs

http://github.com/waseems/inbox2_desktop
C# | 288 lines | 200 code | 45 blank | 43 comment | 13 complexity | 0bcd24f2e5455bd8efb239ca93e51135 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.ComponentModel.Composition;
  5. using System.ComponentModel.Composition.Hosting;
  6. using System.Deployment.Application;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.NetworkInformation;
  10. using System.Reflection;
  11. using Inbox2.Core.Configuration;
  12. using Inbox2.Core.DataAccess;
  13. using Inbox2.Core.Search;
  14. using Inbox2.Core.Storage;
  15. using Inbox2.Core.Threading;
  16. using Inbox2.Core.Threading.Tasks;
  17. using Inbox2.Framework;
  18. using Inbox2.Framework.Deployment;
  19. using Inbox2.Framework.Extensions.ComponentModel;
  20. using Inbox2.Framework.Interfaces.Enumerations;
  21. using Inbox2.Framework.Stats;
  22. using Inbox2.Framework.VirtualMailBox;
  23. using Inbox2.Framework.VirtualMailBox.Entities;
  24. using Inbox2.Platform.Channels;
  25. using Inbox2.Platform.Channels.Entities;
  26. using Inbox2.Platform.Framework;
  27. using Inbox2.Platform.Framework.CloudApi.Logging;
  28. using Inbox2.Platform.Framework.ComponentModel;
  29. using Inbox2.Platform.Framework.Web;
  30. using Inbox2.Platform.Logging;
  31. using Inbox2.UI;
  32. using Newtonsoft.Json;
  33. using PyBinding;
  34. using DebugKeys=Inbox2.Core.Configuration.DebugKeys;
  35. using Document = Inbox2.Framework.VirtualMailBox.Entities.Document;
  36. using Message = Inbox2.Framework.VirtualMailBox.Entities.Message;
  37. using Person = Inbox2.Framework.VirtualMailBox.Entities.Person;
  38. using Profile = Inbox2.Framework.VirtualMailBox.Entities.Profile;
  39. namespace Inbox2.Core
  40. {
  41. public class Startup
  42. {
  43. private static bool _isFirstRun;
  44. public static void PyBinding()
  45. {
  46. // All assemblies used by PyBinding should be added here
  47. Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Inbox2.Platform.Channels.dll"));
  48. // Loads the IronPython runtime
  49. PythonEvaluator evaluator = new PythonEvaluator();
  50. }
  51. /// <summary>
  52. /// Initializes logging.
  53. /// </summary>
  54. public static void Logging(string filename)
  55. {
  56. if (Directory.Exists(DebugKeys.DefaultDataDirectory) == false)
  57. {
  58. Directory.CreateDirectory(DebugKeys.DefaultDataDirectory);
  59. _isFirstRun = true;
  60. }
  61. string logpath = Path.Combine(DebugKeys.DefaultDataDirectory, "logs");
  62. if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);
  63. // Set the log path property which is used by our client logger
  64. log4net.GlobalContext.Properties["LogPath"] = logpath;
  65. using (Stream log4netConfigStream = typeof(Logger).Assembly.GetManifestResourceStream("Inbox2.Platform.Logging." + filename))
  66. Logger.Initialize(new Log4NetLogger(log4netConfigStream));
  67. Logger.Debug("__________________________", LogSource.Startup);
  68. Logger.Debug("Inbox2 application startup", LogSource.Startup);
  69. Logger.Debug("Version: " + Assembly.GetExecutingAssembly().GetName().Version, LogSource.Startup);
  70. Logger.Debug("Data directory is {0}", LogSource.Startup, DebugKeys.DefaultDataDirectory);
  71. }
  72. /// <summary>
  73. /// Initializes the data sources.
  74. /// </summary>
  75. public static void DataSources()
  76. {
  77. DatabaseUtil.InitializeDataStore();
  78. // Right now hardcoded to speed up startup
  79. ClientState.Current.DataService = new SQLiteDataService();
  80. }
  81. /// <summary>
  82. /// Initializes the search index.
  83. /// </summary>
  84. public static void Search()
  85. {
  86. SearchUtil.InitializeSearchStore();
  87. }
  88. /// <summary>
  89. /// Initializes the application plugins.
  90. /// </summary>
  91. public static void CorePlugins()
  92. {
  93. using (new CodeTimer("Startup/CorePlugins"))
  94. {
  95. ClientState.Current.Storage = new OpenFileStorage();
  96. ClientState.Current.Search = new Search.Search();
  97. ClientState.Current.TaskQueue = new TaskQueue();
  98. ClientState.Current.Context = new ClientContext();
  99. ClientState.Current.UndoManager = new UndoManager();
  100. ClientState.Current.ViewController = new ViewController();
  101. }
  102. }
  103. public static void AppPlugins()
  104. {
  105. using (new CodeTimer("Startup/AppPlugins"))
  106. {
  107. // Build MEF catalog of components
  108. var catalog = new AggregateCatalog();
  109. catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "*commands*.dll"));
  110. catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "*.plugins.*.dll"));
  111. var container = new CompositionContainer(catalog);
  112. container.ComposeParts(PluginsManager.Current);
  113. }
  114. }
  115. /// <summary>
  116. /// Initializes the commands.
  117. /// </summary>
  118. public static void Commands()
  119. {
  120. EventBroker.Subscribe(AppEvents.RequestSend, Tasks.Send);
  121. EventBroker.Subscribe(AppEvents.RequestReceive, Tasks.ReceivePrio);
  122. EventBroker.Subscribe(AppEvents.RequestReceive, (int pageSize) => Tasks.ReceivePage(pageSize));
  123. EventBroker.Subscribe(AppEvents.RequestReceive, (ChannelInstance channel) => Tasks.Receive(channel));
  124. EventBroker.Subscribe(AppEvents.RequestSync, Tasks.SyncPrio);
  125. EventBroker.Subscribe(AppEvents.RequestSync, (ChannelInstance channel) => Tasks.Sync(channel));
  126. EventBroker.Subscribe(AppEvents.RequestCommands, Tasks.Commands);
  127. NetworkChange.NetworkAvailabilityChanged += delegate
  128. {
  129. if (NetworkInterface.GetIsNetworkAvailable())
  130. {
  131. Tasks.Send();
  132. Tasks.Commands();
  133. Tasks.Receive();
  134. }
  135. };
  136. }
  137. /// <summary>
  138. /// Initializes the database and stuff.
  139. /// </summary>
  140. public static void Plumbing()
  141. {
  142. var clientId = SettingsManager.ClientSettings.AppConfiguration.ClientId;
  143. var baseUrl = String.Format("http://download{0}.inbox2.com/",
  144. String.IsNullOrEmpty(CommandLine.Current.Environment) ? String.Empty : "." + CommandLine.Current.Environment);
  145. Migrate.Up(typeof(ChannelConfig));
  146. Migrate.Up(typeof(Conversation));
  147. Migrate.Up(typeof(Message));
  148. Migrate.Up(typeof(Document));
  149. Migrate.Up(typeof(DocumentVersion));
  150. Migrate.Up(typeof(Person));
  151. Migrate.Up(typeof(Profile));
  152. Migrate.Up(typeof(UserStatus));
  153. Migrate.Up(typeof(UserStatusAttachment));
  154. Migrate.Up(typeof(QueuedCommand));
  155. Migrate.Up(typeof(FeedItem));
  156. var appVersion = Assembly.GetExecutingAssembly().GetName().Version;
  157. var savedVersion = SettingsManager.ClientSettings.Version;
  158. Logger.Warn("Saved version {0}", LogSource.Startup, savedVersion);
  159. if (_isFirstRun || Environment.CommandLine.Contains("/firstrun"))
  160. {
  161. HttpServiceRequest.Post(baseUrl + "version/install",
  162. String.Format("clientId={0}&version={1}", clientId, appVersion));
  163. }
  164. if (_isFirstRun == false && appVersion > savedVersion)
  165. {
  166. Logger.Debug("Upgrade detected, performing nescessary upgrade actions", LogSource.Startup);
  167. // Get all upgrades
  168. UpgradeActionBase.Upgrades.AddRange(typeof(Startup)
  169. .Assembly.GetTypes()
  170. .Where(t => t.IsSubclassOf(typeof (UpgradeActionBase)))
  171. .Select(t => (UpgradeActionBase) Activator.CreateInstance(t))
  172. .Where(i => i.TargetVersion > savedVersion)
  173. .OrderBy(i => i.TargetVersion));
  174. UpgradeActionBase.Upgrades.ForEach(i => i.Upgrade());
  175. HttpServiceRequest.Post(baseUrl + "version/upgrade",
  176. String.Format("clientId={0}&from={1}&to={2}", clientId, savedVersion, appVersion));
  177. }
  178. // Save current version
  179. SettingsManager.ClientSettings.Version = appVersion;
  180. }
  181. /// <summary>
  182. /// Loads and initializes the channels.
  183. /// </summary>
  184. public static void Channels()
  185. {
  186. var channels = ClientState.Current.DataService.SelectAll<ChannelConfig>();
  187. foreach (var channel in channels)
  188. ChannelsManager.Add(ChannelFactory.Create(channel));
  189. }
  190. /// <summary>
  191. /// Initializes the type converters.
  192. /// </summary>
  193. public static void TypeConverters()
  194. {
  195. TypeDescriptor.AddAttributes(typeof(SourceAddress),
  196. new TypeConverterAttribute(typeof(SourceAddressConverter)));
  197. TypeDescriptor.AddAttributes(typeof(SourceAddressCollection),
  198. new TypeConverterAttribute(typeof(SourceAddressCollectionConverter)));
  199. TypeDescriptor.AddAttributes(typeof(Stream),
  200. new TypeConverterAttribute(typeof(StreamConverter)));
  201. }
  202. /// <summary>
  203. /// Gets the app version.
  204. /// </summary>
  205. /// <returns></returns>
  206. public static Version GetAppVersion()
  207. {
  208. //Get the version of the currently executing Assembly
  209. Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
  210. //Check to see if we are ClickOnce Deployed
  211. if (ApplicationDeployment.IsNetworkDeployed)
  212. currentVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion;
  213. return currentVersion;
  214. }
  215. /// <summary>
  216. /// Initializes the keyboard hooks.
  217. /// </summary>
  218. public static void KeyboardHooks()
  219. {
  220. //Keyboard.Initialize();
  221. }
  222. public static void LoadStats()
  223. {
  224. // Check if we have a saved logs
  225. if (SettingsManager.ClientSettings.ContextSettings.ContainsKey("/Application/StoredStats"))
  226. {
  227. var storedlogs = SettingsManager.ClientSettings.ContextSettings["/Application/StoredStats"];
  228. if (storedlogs != null)
  229. {
  230. // Deserialize logs
  231. using (var sr = new StringReader((string) storedlogs))
  232. {
  233. var ser = new JsonSerializer();
  234. var logs = (List<TraceInfo>)ser.Deserialize(sr, typeof(List<TraceInfo>));
  235. ClientStats.ReEnqueue(logs);
  236. SettingsManager.ClientSettings.ContextSettings.Remove("/Application/StoredStats");
  237. SettingsManager.Save();
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }