Esempio n. 1
0
 public VersionMini(VersionInfo vers, FTObjects ftobjects)
 {
     InitializeComponent();
     m_VersionInfo = vers;
     m_FTObjects = ftobjects;
     SetVersion();
 }
Esempio n. 2
0
 public VersionLeaf(VersionInfo vers)
 {
     this.m_VersionInfo = vers;
     this.Visible = true;
     InitializeComponent();
     if (m_VersionInfo != null)
     {
         this.VersionLabelBig.Text = m_VersionInfo.versionName;
     }
     else
     {
         this.VersionLabelBig.Text = "Big Version";
     }
     if (m_VersionInfo != null && m_VersionInfo.userVersName != null)
     {
         StringBuilder bil = new StringBuilder();
         foreach (string name in m_VersionInfo.userVersName)
         {
             bil.Append(name + "\n");
         }
         this.VersionLabel.Text = bil.ToString();
     }
     else
     {
         this.VersionLabel.Text = "Small Version";
     }
 }
        private void WebClient_OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs downloadStringCompletedEventArgs)
        {
            // Pega a referência do resultado            
            var result = downloadStringCompletedEventArgs.Result;
            // Deserializa o XML recebido do site
            latestVersion = SerializationHelper.ReadFromXml<VersionInfo>(result);
            // Libera o WebClient da memória
            ((WebClient)sender).Dispose();
            
            // Atualiza as configurações, informando a data da última checagem de atualização
            Properties.Settings.Default.LastTimeCheckedUpdate = DateTime.Now;
            Properties.Settings.Default.Save();

            // Atualiza as configurações
            Properties.Settings.Default.UpdateAvailable = UpdateAvailable;
            Properties.Settings.Default.Save();

            // Atualização disponível
            if (!UpdateAvailable) return;            

            // Define o local para salvar o arquivo
            downloadedFileName = downloadedFileDir + System.IO.Path.GetFileName(latestVersion.downloadURL);
            // Baixa atualização
            DownloadUpdate(latestVersion.downloadURL, downloadedFileName);
        }
        public ChangeLogEntry CreateEntry(VersionInfo version,string text)
        {
            ChangeLogEntry entry = new ChangeLogEntry();
            entry.Version = version;
            entry.Text = text;

            return entry;
        }
Esempio n. 5
0
		static VitaNexCore()
		{
			_INITQueue = new Queue<Tuple<string, string>>();
			_INITHandlers = new Dictionary<string, Action<string>>();

			_INITVersion = "2.2.0.0";

			Version = null;

			if (!Directory.Exists(IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/VitaNexCore")))
			{
				FirstBoot = true;
			}

			BaseDirectory = IOUtility.EnsureDirectory(Core.BaseDirectory + "/VitaNexCore");

			if (!File.Exists(BaseDirectory + "/FirstBoot.vnc"))
			{
				FirstBoot = true;

				IOUtility.EnsureFile(BaseDirectory + "/FirstBoot.vnc")
						 .AppendText(
							 true,
							 "This file serves no other purpose than to identify if",
							 "the software has been initialized for the first time. ",
							 "To re-initialize 'First-Boot' mode, simply delete this",
							 "file before starting the application.");
			}

			// HACK: See FindRootDirectory summary.
			var root = FindRootDirectory(Core.BaseDirectory + "/Scripts/VitaNex");
			
			if (root == null || !root.Exists)
			{
				return;
			}

			RootDirectory = root;

			ParseVersion();
			ParseINIT();

			RegisterINITHandler(
				"ROOT_DIR",
				path =>
				{
					root = FindRootDirectory(path);

					if (root == null || !root.Exists)
					{
						return;
					}

					RootDirectory = root;

					ParseVersion();
				});
		}
Esempio n. 6
0
 public void removeVersion(VersionInfo version)
 {
     DataRow dat;
     VersionInfoFromDataRow.TryGetValue(version, out dat);
     if (dat != null)
     {
         this.Rows.Remove(dat);
         VersionInfoFromDataRow.Remove(version);
     }
 }
        public void addVersion(VersionInfo vers)
        {
            List<VersionBox> newC = mana.returnChangeAdd(vers);
            this.SuspendLayout();
            VersionLeaf vler;
            //Todo if there is a row add then everything must be redrawn
            //make that more clear bu setting a variable
            //then check that and redraw
            //if (mana.removeBox == null && newC == null)
            //{
            //    addAllFromMana();
            //}
            //else
            //{
            //    foreach (BoxLoc bo in mana.removeBox)
            //    {
            //        VersionBoxFromString.TryGetValue("row" + bo.row + "col" + bo.col, out vler);
            //        if (vler != null)
            //        {
            //            vler.Visible = false;
            //        }
            //    }
            //    this.tableLayoutPanel1.ColumnCount = mana.Col + 1;
            //    this.tableLayoutPanel1.RowCount = mana.Row + 1;
            //    foreach (VersionBox vb in newC)
            //    {
            //        VersionBoxFromString.TryGetValue("row" + vb.Row + "col" + vb.Col, out vler);
            //        if (vler != null)
            //        {
            //            vler.setVersionInfo(vb.m_version);
            //        }
            //        else
            //        {
            //            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            //            VersionLeaf leaf = new VersionLeaf(vb.m_version);
            //            leaf.setText("Col: " + vb.Col + " Row: " + vb.Row + " ColSpan: " + vb.ColSpan);
            //            leaf.Anchor = System.Windows.Forms.AnchorStyles.None;
            //            leaf.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            //            leaf.Location = new System.Drawing.Point(4, 4);
            //            leaf.Size = new System.Drawing.Size(150, 150);
            //            this.tableLayoutPanel1.Controls.Add(leaf, vb.Col, vb.Row);
            //            VersionBoxFromString["row" + vb.Row + "col" + vb.Col] = leaf;
            //            if (vb.ColSpan > 0)
            //            {
            //                this.tableLayoutPanel1.SetColumnSpan(leaf, vb.ColSpan);
            //            }
            //            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            //        }

            //    }
            //}
            //this.ResumeLayout(false);
            //this.PerformLayout();
        }
        public override void ExecuteVersioningStrategy(string currentVersion, string desiredVersion)
        {
            Logger.InfoFormat("No version history information found, creating history at version '{0}'..",
                desiredVersion);
            var version = new VersionInfo {Version = desiredVersion};
            CreateNewVersion(version);
            Logger.InfoFormat("Version '{0}' recorded.", desiredVersion);

            FromVersion = "0";
            ToVersion = version.Version;
        }
Esempio n. 9
0
        public VersionFile GetVersionInfo(VersionInfo build)
        {
            if (!Configured())
                return null;
            if (!File.Exists(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml"))
                return null;

            var fileinfo = new VersionFile();
            fileinfo.Load(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");
            return fileinfo;
        }
Esempio n. 10
0
 public void setVersionInfo(VersionInfo vers)
 {
     this.m_VersionInfo = vers;
     this.VersionLabelBig.Text = vers.versionName;
     StringBuilder bil = new StringBuilder();
     foreach (string name in m_VersionInfo.userVersName)
     {
         bil.Append(name + "\n");
     }
     this.VersionLabel.Text = bil.ToString();
     this.Visible = true;
 }
Esempio n. 11
0
		void CreateControlFromInfo ()
		{
			var lw = new LogWidget (info);
			
			widget = lw;
			info.Updated += OnInfoUpdated;
			lw.History = this.info.History;
			vinfo   = this.info.Item.VersionInfo;
		
			if (WorkbenchWindow != null)
				widget.SetToolbar (WorkbenchWindow.GetToolbar (this));
		}
Esempio n. 12
0
        public VersionMini(VersionInfo vers, FTObjects ftobjects, bool removed)
        {
            InitializeComponent();

                m_VersionInfo = vers;
                m_FTObjects = ftobjects;
                SetVersion();
                if (removed == true)
                {
                    iSetRemoved(true);
                }
        }
		public override void Deserialize(GenericReader reader)
		{
			base.Deserialize(reader);

			int version = reader.GetVersion();

			switch (version)
			{
				case 0:
					Version = new VersionInfo(reader);
					break;
			}
		}
Esempio n. 14
0
        public bool UpdateVersionDescription(VersionInfo build, string description)
        {
            if (!Configured())
                return false;
            if (!File.Exists(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml"))
                return false;

            var fileinfo = new VersionFile();
            fileinfo.Load(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");
            fileinfo.Description = description;
            fileinfo.Save(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml");

            return true;
        }
Esempio n. 15
0
 public CalendarPanel(VersionInfo vers)
 {
     InitializeComponent();
     this.DateLabel.Text = vers.date.ToLongDateString();
     this.TimeLabel.Text = vers.date.ToLongTimeString();
     this.VersionsListBox.Items.Add(vers.versionName);
     if (vers.userVersName != null)
     {
         foreach (string v in vers.userVersName)
         {
             this.VersionsListBox.Items.Add(v);
         }
     }
 }
Esempio n. 16
0
			public DiffData (Repository vc, FilePath root, VersionInfo info, bool remote)
			{
				VersionInfo = info;
				Diff = new Lazy<DiffInfo> (() => {
					try {
						DiffInfo result = null;
						if (!remote)
							result = vc.GenerateDiff (root, info);
						return result ?? vc.PathDiff (root, new [] { info.LocalPath }, remote).FirstOrDefault ();
					} catch (Exception ex) {
						Exception = ex;
						return null;
					}
				});
			}
Esempio n. 17
0
        public static VersionInfo Get()
        {
            if (versionInfo == null)
            {
                lock (lockObj)
                {
                    if (versionInfo == null)
                    {
                        versionInfo = get();
                    }
                }
            }

            return versionInfo;
        }
Esempio n. 18
0
		public void Start ()
		{
			ThreadPool.QueueUserWorkItem (delegate {
				try {
					History      = Item.Repository.GetHistory (Item.Path, null);
					VersionInfo  = Item.Repository.GetVersionInfo (Item.Path, false);
				} catch (Exception ex) {
					LoggingService.LogError ("Error retrieving history", ex);
				}
				
				DispatchService.GuiDispatch (delegate {
					OnUpdated (EventArgs.Empty);
				});
			});
		}
Esempio n. 19
0
		void CreateControlFromInfo ()
		{
			this.vc = info.Item.Repository;
			this.filepath = info.Item.Path;
			var lw = new LogWidget (info);
			
			widget = lw;
			info.Updated += delegate {
				lw.History = this.info.History;
				vinfo   = this.info.VersionInfo;
			};
			lw.History = this.info.History;
			vinfo   = this.info.VersionInfo;
		
		}
        public object Get(VersionInfo request)
        {
            var availableMigrations = Assembly.GetTypes()
                .Where(t => t.IsDefined(typeof(MigrationAttribute), true))
                .Select(t =>
                {
                    var m = (MigrationAttribute)t.GetCustomAttributes(typeof(MigrationAttribute), true).First();
                    return new VersionInfo 
                    { 
                        Description = m.Description ?? t.Name, 
                        Version = m.Version,
                        IsAvailable = true,
                    };
                })
                .ToList();

            using(var con = Database.OpenDbConnection())
            {
                List<VersionInfo> appliedMigrations;

                if (con.TableExists("VersionInfo"))
                {
                    appliedMigrations = con.Select<VersionInfo>();
                }
                else
                {
                    appliedMigrations = new List<VersionInfo>();
                }

                return new VersionInfoResponse
                {
                    Migrations = appliedMigrations
                        .Concat(availableMigrations)
                        .ToLookup(v => v.Version)
                        .Select(g => g.Aggregate((v1, v2) => new VersionInfo
                        {
                            Version = v1.Version,
                            Description = v1.Description ?? v2.Description,
                            AppliedOn = v1.AppliedOn ?? v2.AppliedOn,
                            IsAvailable = v1.IsAvailable || v2.IsAvailable,
                        }))
                        .OrderByDescending(v => v.Version)
                        .ToList(),
                    Info = appliedMigrations.Except(availableMigrations).Any() ? "Warning: Database has migrations applied that are not available in the current migration assembly.  Rollback may not be possible." : null,
                    Database = con.Database,
                };
            }            
        }
Esempio n. 21
0
 public static void AddUserVersionButton_Click( VersionInfo VersionInfo, EventArgs e, Panel Caller)
 {
     if (VersionInfo != null)
     {
         Util.UserDebug("Add User Version Button Clicked " + VersionInfo.versionName);
         UserVersionForm uservers = new UserVersionForm(VersionInfo, m_FTObjects.AllUserVersions);
         DialogResult res = uservers.ShowDialog(Caller);
         if (res == DialogResult.OK)
         {
             UserVersVer ver = new UserVersVer();
             ver.uservers = uservers;
             ver.versionInfo = VersionInfo;
             new Thread(new ParameterizedThreadStart(HandleAddUser)).Start(ver);
         }
     }
 }
 public void SetVersionInfo(VersionInfo vi)
 {
     this.versionInfo = vi;
     string version = GameInfo.instance.version;
     if (vi.isMandatory == 1)
     {
         this.descTM.text = string.Format(Localization.Localize("NewVersionNoticeContent2"), version, vi.newVersionId);
         this.mandatoryObj.SetActive(true);
         this.optionObj.SetActive(false);
     }
     else
     {
         this.descTM.text = string.Format(Localization.Localize("NewVersionNoticeContent1"), version, vi.newVersionId);
         this.optionObj.SetActive(true);
         this.mandatoryObj.SetActive(false);
     }
     this.descTM.Commit();
 }
Esempio n. 23
0
            public static bool TryParse(string value, out VersionInfo info)
            {
                if (value.Length > 1 && value.EndsWith("b"))
                {
                    value = value.Substring(0, value.Length - 1);
                }

                if (string.IsNullOrEmpty(value))
                {
                    info = default(VersionInfo);
                    return false;
                }
                
                string[] tokens = value.Split('.');
                if (tokens.Length != 3)
                {
                    info = default(VersionInfo);
                    return false;
                }
                
                int major;
                if (!int.TryParse(tokens[0], out major))
                {
                    info = default(VersionInfo);
                    return false;
                }
                
                int minor;
                if (!int.TryParse(tokens[1], out minor))
                {
                    info = default(VersionInfo);
                    return false;
                }
                
                int maintenance;
                if (!int.TryParse(tokens[2], out maintenance))
                {
                    info = default(VersionInfo);
                    return false;
                }
                
                info = new VersionInfo(major, minor, maintenance);
                return true;
            }
Esempio n. 24
0
		public LogView (string filepath, bool isDirectory, Revision [] history, Repository vc) 
			: base (Path.GetFileName (filepath) + " Log")
		{
			try {
				this.vinfo = vc.GetVersionInfo (filepath, VersionInfoQueryFlags.IgnoreCache);
			}
			catch (Exception ex) {
				MessageService.ShowError (GettextCatalog.GetString ("Version control command failed."), ex);
			}
			
			// Widget setup
			VersionControlDocumentInfo info  =new VersionControlDocumentInfo (null, null, vc);
			info.History = history;
			info.Item.VersionInfo = vinfo;
			var lw = new LogWidget (info);
			
			widget = lw;
			lw.History = history;
		}
Esempio n. 25
0
 public override VersionInfo Version(string id)
 {
   RegistryKey key =
     Registry.LocalMachine.OpenSubKey(
       "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MediaPortal TV Server");
   if (key != null)
   {
     var version = new VersionInfo
                     {
                       Build = ((int)key.GetValue("VersionBuild", 0)).ToString(),
                       Major = ((int)key.GetValue("VersionMajor", 0)).ToString(),
                       Minor = ((int)key.GetValue("VersionMinor", 0)).ToString(),
                       Revision = ((int)key.GetValue("VersionRevision", 0)).ToString(),
                     };
     key.Close();
     return version;
   }
   return new VersionInfo();
 }
        protected VersionInfo CreateNewVersion(VersionInfo versionInfo = null)
        {
            if (versionInfo == null)
                versionInfo = new VersionInfo();

            versionInfo.EnteredBy = string.Format(@"{0}\{1}",
                Environment.UserDomainName,
                Environment.UserName);

            versionInfo.EntryDate = DateTime.Now;

            using (var connection = _configuration.GetConnection())
            {
                var id = connection.Insert(versionInfo);
                if (versionInfo.Id == 0)
                    versionInfo.Id = id;
            }

            return versionInfo;
        }
Esempio n. 27
0
 public UserVersionForm(VersionInfo versioninfo, List<string>  AllUserVersions)
 {
     InitializeComponent();
     m_VersionInfo = versioninfo;
     m_AllUserVersions = AllUserVersions;
     StopUserVersionPanelList = new PanelList<string>();
     PanelFromUserVersion panelFromDat = new PanelFromUserVersion();
     panelFromDat.m_UserVersionForm = this;
     StopUserVersionPanelList.PanelFromData = panelFromDat;
     this.VersionPanel.Controls.Add(StopUserVersionPanelList);
     NewUserVersions = new List<string>();
     RemoveUserVersions = new List<string>();
     ReUseUserVersions = new List<string>();
     LastUserVersions = new List<string>();
     UsedUserVersions = new List<string>();
     ContinueUserVersions = new List<string>();
     SetUserVersions(versioninfo.UserVersionsThatContain);
     SetReUseUserVersion(versioninfo.UserVersionsThatContain, AllUserVersions);
     this.DialogResult = DialogResult.Cancel;
     StopUserVersionPanelList.ExtraRowSpace = 5;
 }
Esempio n. 28
0
        public Search(DataManager datamanager)
        {
            InitializeComponent();
            m_DataManager = datamanager;

            SeachData = new List<VersionInfo>();
            VersionInfo versioninfo = new VersionInfo();
            versioninfo.versionName = "Test Version Name";
            versioninfo.date = DateTime.Now;
            versioninfo.FreeText = "Test Free Text";
            versioninfo.UserVersName = new List<string>();
            versioninfo.UserVersName.Add("VersionName1");
            versioninfo.UserVersName.Add("VersionName2");
            SeachData.Add(versioninfo);
              //  this.dataGridView1.Rows.Add();
             //   d this.dataGridView1.Rows[0];
               shearch = new SearchDataTable(datamanager, this.dataGridView1);

            this.dataGridView1.DataSource = shearch;

            Setu();
        }
Esempio n. 29
0
 public static Dictionary<string, VersionInfo> ReadVersionNumFile(XmlElement xmlRoot)
 {
     var dicVersionNum = new Dictionary<string, VersionInfo>();
     if (xmlRoot != null)
     {
         foreach (XmlNode node in xmlRoot.ChildNodes)
         {
             if ((node is XmlElement) == false)
             {
                 continue;
             }
             var element = (node as XmlElement);
             var file = element.GetAttribute("FileName");
             var md5 = element.GetAttribute("Md5");
             var num = XmlConvert.ToInt32(element.GetAttribute("Num"));
             if (dicVersionNum.ContainsKey(file) == false)
             {
                 var versionInfo = new VersionInfo(md5, num);
                 dicVersionNum.Add(file, versionInfo);
             }
         }
     }
     return dicVersionNum;
 }
Esempio n. 30
0
    public string ReplaceTokens(string template, ModuleDefinition moduleDefinition, VersionInfo ver)
    {
        var assemblyVersion = moduleDefinition.Assembly.Name.Version;
        var branch = ver.BranchName;

        template = template.Replace("%version%", assemblyVersion.ToString());
        template = template.Replace("%version1%", assemblyVersion.ToString(1));
        template = template.Replace("%version2%", assemblyVersion.ToString(2));
        template = template.Replace("%version3%", assemblyVersion.ToString(3));
        template = template.Replace("%version4%", assemblyVersion.ToString(4));

        template = template.Replace("%revno%", ver.Revision.ToString());

        template = template.Replace("%branch%", branch);

        template = template.Replace("%haschanges%", ver.HasChanges ? "HasChanges" : string.Empty);

        template = template.Replace("%user%", FormatUserName());
        template = template.Replace("%machine%", Environment.MachineName);

        template = reEnvironmentToken.Replace(template, FormatEnvironmentVariable);

        return template.Trim();
    }
Esempio n. 31
0
 public static string GetAppCodeVersion()
 {
     return(VersionInfo.GetCodeVersion());
 }
Esempio n. 32
0
        public void Register(ContainerBuilder builder)
        {
            const int ConnectionPoolSize = 10;

            string edgeHubConnectionString = $"{this.configuration[EdgeHubConstants.ConfigKey.IotHubConnectionString]};ModuleId=$edgeHub";
            IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeHubConnectionString);
            var topics = new MessageAddressConversionConfiguration(this.inboundTemplates, this.outboundTemplates);

            builder.RegisterModule(new LoggingModule());

            var mqttSettingsConfiguration = new Mock <IConfiguration>();

            mqttSettingsConfiguration.Setup(c => c.GetSection(It.IsAny <string>())).Returns(Mock.Of <IConfigurationSection>(s => s.Value == null));

            var experimentalFeatures = new ExperimentalFeatures(true, false, false, true);

            builder.RegisterBuildCallback(
                c =>
            {
                // set up loggers for dotnetty
                var loggerFactory = c.Resolve <ILoggerFactory>();
                InternalLoggerFactory.DefaultFactory = loggerFactory;

                var eventListener = new LoggerEventListener(loggerFactory.CreateLogger("ProtocolGateway"));
                eventListener.EnableEvents(CommonEventSource.Log, EventLevel.Informational);
            });

            var versionInfo   = new VersionInfo("v1", "b1", "c1");
            var metricsConfig = new MetricsConfig(true, new MetricsListenerConfig());
            var backupFolder  = Option.None <string>();

            string      storageFolder = string.Empty;
            StoreLimits storeLimits   = null;

            if (!int.TryParse(this.configuration["TimeToLiveSecs"], out int timeToLiveSecs))
            {
                timeToLiveSecs = -1;
            }

            if (long.TryParse(this.configuration["MaxStorageBytes"], out long maxStorageBytes))
            {
                storeLimits = new StoreLimits(maxStorageBytes);
            }

            var storeAndForwardConfiguration = new StoreAndForwardConfiguration(timeToLiveSecs, storeLimits);

            if (bool.TryParse(this.configuration["UsePersistentStorage"], out bool usePersistentStorage) && usePersistentStorage)
            {
                storageFolder = GetOrCreateDirectoryPath(this.configuration["StorageFolder"], EdgeHubConstants.EdgeHubStorageFolder);
            }

            if (bool.TryParse(this.configuration["EnableNonPersistentStorageBackup"], out bool enableNonPersistentStorageBackup))
            {
                backupFolder = Option.Some(this.configuration["BackupFolder"]);
            }

            var    testRoutes   = this.routes;
            string customRoutes = this.configuration["Routes"];

            if (!string.IsNullOrWhiteSpace(customRoutes))
            {
                testRoutes = JsonConvert.DeserializeObject <IDictionary <string, string> >(customRoutes);
            }

            builder.RegisterModule(
                new CommonModule(
                    string.Empty,
                    iotHubConnectionStringBuilder.HostName,
                    iotHubConnectionStringBuilder.DeviceId,
                    iotHubConnectionStringBuilder.ModuleId,
                    string.Empty,
                    Option.None <string>(),
                    AuthenticationMode.CloudAndScope,
                    Option.Some(edgeHubConnectionString),
                    false,
                    usePersistentStorage,
                    storageFolder,
                    Option.None <string>(),
                    Option.None <string>(),
                    TimeSpan.FromHours(1),
                    false,
                    this.trustBundle,
                    string.Empty,
                    metricsConfig,
                    enableNonPersistentStorageBackup,
                    backupFolder,
                    Option.None <ulong>()));

            builder.RegisterModule(
                new RoutingModule(
                    iotHubConnectionStringBuilder.HostName,
                    iotHubConnectionStringBuilder.DeviceId,
                    iotHubConnectionStringBuilder.ModuleId,
                    Option.Some(edgeHubConnectionString),
                    testRoutes,
                    true,
                    storeAndForwardConfiguration,
                    ConnectionPoolSize,
                    false,
                    versionInfo,
                    Option.Some(UpstreamProtocol.Amqp),
                    TimeSpan.FromSeconds(5),
                    101,
                    TimeSpan.FromSeconds(3600),
                    true,
                    TimeSpan.FromSeconds(20),
                    false,
                    Option.None <TimeSpan>(),
                    Option.None <TimeSpan>(),
                    false,
                    10,
                    10,
                    false,
                    TimeSpan.FromHours(1),
                    experimentalFeatures));

            builder.RegisterModule(new HttpModule());
            builder.RegisterModule(new MqttModule(mqttSettingsConfiguration.Object, topics, this.serverCertificate, false, false, false, this.sslProtocols));
            builder.RegisterModule(new AmqpModule("amqps", 5671, this.serverCertificate, iotHubConnectionStringBuilder.HostName, true, this.sslProtocols));
        }
Esempio n. 33
0
        /// <summary>
        /// 获取版本信息
        /// </summary>
        /// <returns></returns>
        public ReturnResult <VersionInfo> GetVersionInfo()
        {
            VersionInfo version = new VersionInfo();

            version.VersionNumber = 0;
            try
            {
                //获取txt文件中的版本号和更新内容
                string[] lines           = File.ReadAllLines(GetVersionFilePath());
                bool     isVersionNumber = false;
                bool     isVersion       = false;
                bool     isUpdateContent = false;
                foreach (string line in lines)
                {
                    if (isVersionNumber)
                    {
                        try
                        {
                            version.VersionNumber = Convert.ToInt32(line);
                        }
                        catch { }//转错不处理

                        isVersionNumber = false;
                    }
                    else if (isVersion)
                    {
                        version.Version = line;
                        isVersion       = false;
                    }
                    else if (isUpdateContent)
                    {
                        version.UpdateContent += line + "\r\n";
                    }

                    if (line != string.Empty && line.Contains("VersionNumber"))
                    {
                        isVersionNumber = true;
                    }
                    if (line != string.Empty && line.Contains("Version"))
                    {
                        isVersion = true;
                    }
                    if (line != string.Empty && line.Contains("UpdateContent"))
                    {
                        isUpdateContent = true;
                    }
                }
                if (string.IsNullOrEmpty(version.Version))
                {
                    version.Version = "1.0.0";
                }
                if (string.IsNullOrEmpty(version.UpdateContent))
                {
                    version.UpdateContent = "优化了主要流程!";
                }
                version.DownloadAddress = ConfigurationManager.AppSettings["Localhost"]
                                          + @"/Download/junzhi.apk";

                return(new ReturnResult <VersionInfo>(1, version));
            }
            catch (Exception ex)
            {
                return(new ReturnResult <VersionInfo>(-1, ex.Message));
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Create documentation output specification.
        /// </summary>
        /// <param name="rootPath">
        /// The root path.
        /// </param>
        /// <param name="outputPath">
        /// The output path.
        /// </param>
        /// <param name="outputType">
        /// The output type.
        /// </param>
        /// <param name="debugMode"></param>
        /// <returns>
        /// The <see cref="IDocsOutput"/>.
        /// </returns>
        private static IDocsOutput CreateDocumentationOutputSpecification(string rootPath, string outputPath, OutputType outputType, VersionInfo version, bool debugMode)
        {
            //var rootUrl = @"http://ravendb.net/docs/" + version.VersionAlias + "/";
            var rootUrl = @"http://localhost/RavenDoc/version_3/html-compiled/";

            if (outputType == OutputType.Markdown)
            {
                return(new MarkdownDocsOutput
                {
                    ContentType = OutputType.Markdown,
                    OutputPath = outputPath,
                    RootUrl = rootUrl,
                    CompilationMode = version.CompilationMode
                });
            }

            if (outputType == OutputType.Html)
            {
                IDocsOutput output = new HtmlDocsOutput
                {
                    ContentType  = OutputType.Html,
                    OutputPath   = outputPath,
                    PageTemplate =
                        File.ReadAllText(
                            Path.Combine(rootPath, version.VersionPath, @"html-template.html")),
                    RootUrl         = rootUrl,
                    ImagesPath      = debugMode ? "images/" : null,
                    CompilationMode = version.CompilationMode,
                    DebugMode       = debugMode
                };
                return(output);
            }

            return(null);
        }
Esempio n. 35
0
        public void Register(ContainerBuilder builder)
        {
            const int ConnectionPoolSize = 10;

            string edgeHubConnectionString = $"{this.configuration[Constants.ConfigKey.IotHubConnectionString]};ModuleId=$edgeHub";
            IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeHubConnectionString);
            var topics = new MessageAddressConversionConfiguration(this.inboundTemplates, this.outboundTemplates);

            builder.RegisterModule(new LoggingModule());

            var mqttSettingsConfiguration = new Mock <IConfiguration>();

            mqttSettingsConfiguration.Setup(c => c.GetSection(It.IsAny <string>())).Returns(Mock.Of <IConfigurationSection>(s => s.Value == null));

            builder.RegisterBuildCallback(
                c =>
            {
                // set up loggers for dotnetty
                var loggerFactory = c.Resolve <ILoggerFactory>();
                InternalLoggerFactory.DefaultFactory = loggerFactory;

                var eventListener = new LoggerEventListener(loggerFactory.CreateLogger("ProtocolGateway"));
                eventListener.EnableEvents(CommonEventSource.Log, EventLevel.Informational);
            });

            var versionInfo = new VersionInfo("v1", "b1", "c1");
            var storeAndForwardConfiguration = new StoreAndForwardConfiguration(-1);
            var metricsConfig = new MetricsConfig(false, new MetricsListenerConfig());

            builder.RegisterModule(
                new CommonModule(
                    string.Empty,
                    iotHubConnectionStringBuilder.HostName,
                    iotHubConnectionStringBuilder.DeviceId,
                    iotHubConnectionStringBuilder.ModuleId,
                    string.Empty,
                    Option.None <string>(),
                    AuthenticationMode.CloudAndScope,
                    Option.Some(edgeHubConnectionString),
                    false,
                    false,
                    string.Empty,
                    Option.None <string>(),
                    Option.None <string>(),
                    TimeSpan.FromHours(1),
                    false,
                    this.trustBundle,
                    string.Empty,
                    metricsConfig));

            builder.RegisterModule(
                new RoutingModule(
                    iotHubConnectionStringBuilder.HostName,
                    iotHubConnectionStringBuilder.DeviceId,
                    iotHubConnectionStringBuilder.ModuleId,
                    Option.Some(edgeHubConnectionString),
                    this.routes,
                    false,
                    storeAndForwardConfiguration,
                    ConnectionPoolSize,
                    false,
                    versionInfo,
                    Option.Some(UpstreamProtocol.Amqp),
                    TimeSpan.FromSeconds(5),
                    101,
                    TimeSpan.FromSeconds(3600),
                    true,
                    TimeSpan.FromSeconds(20),
                    Option.None <TimeSpan>(),
                    Option.None <TimeSpan>(),
                    false,
                    10,
                    10,
                    false,
                    false,
                    TimeSpan.FromHours(1),
                    true));

            builder.RegisterModule(new HttpModule());
            builder.RegisterModule(new MqttModule(mqttSettingsConfiguration.Object, topics, this.serverCertificate, false, false, false));
            builder.RegisterModule(new AmqpModule("amqps", 5671, this.serverCertificate, iotHubConnectionStringBuilder.HostName, true));
        }
Esempio n. 36
0
 public Method(string name, VersionInfo version, string[] args)
 {
     _methodName = name;
     _version    = version;
     _args       = args;
 }
 internal protected virtual VersionControlOperation GetSupportedOperations(Repository repo, VersionInfo vinfo, VersionControlOperation defaultValue)
 {
     if (vinfo.IsVersioned && File.Exists(vinfo.LocalPath) && !Directory.Exists(vinfo.LocalPath) && vinfo.HasLocalChange(VersionStatus.ScheduledDelete))
     {
         defaultValue |= VersionControlOperation.Add;
     }
     return(defaultValue);
 }
Esempio n. 38
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // Get Version, database info and executing assembly location
            lRockVersion.Text = string.Format("{0} <small>({1})</small>", VersionInfo.GetRockProductVersionFullName(), VersionInfo.GetRockProductVersionNumber());
            if (File.Exists(Server.MapPath("~/build.info")))
            {
                lRockVersion.Text += " - " + File.ReadAllText(Server.MapPath("~/build.info"));
            }
            lClientCulture.Text  = System.Globalization.CultureInfo.CurrentCulture.ToString();
            lDatabase.Text       = GetDbInfo();
            lSystemDateTime.Text = DateTime.Now.ToString("G") + " " + DateTime.Now.ToString("zzz");
            lRockTime.Text       = Rock.RockDateTime.Now.ToString("G") + " " + Rock.RockDateTime.OrgTimeZoneInfo.BaseUtcOffset.ToString();
            var currentProcess = System.Diagnostics.Process.GetCurrentProcess();

            if (currentProcess != null && currentProcess.StartTime != null)
            {
                lProcessStartTime.Text = currentProcess.StartTime.ToString("G") + " " + DateTime.Now.ToString("zzz");
            }
            else
            {
                lProcessStartTime.Text = "-";
            }

            lExecLocation.Text   = Assembly.GetExecutingAssembly().Location;
            lLastMigrations.Text = GetLastMigrationData();

            var transactionQueueStats = RockQueue.TransactionQueue.ToList().GroupBy(a => a.GetType().Name).ToList().Select(a => new { Name = a.Key, Count = a.Count() });

            lTransactionQueue.Text = transactionQueueStats.Select(a => string.Format("{0}: {1}", a.Name, a.Count)).ToList().AsDelimited("<br/>");

            lCacheOverview.Text = GetCacheInfo();
            lRoutes.Text        = GetRoutesInfo();

            // register btnDumpDiagnostics as a PostBackControl since it is returning a File download
            ScriptManager scriptManager = ScriptManager.GetCurrent(Page);

            scriptManager.RegisterPostBackControl(btnDumpDiagnostics);
        }
Esempio n. 39
0
        public override void MoveDirectory(FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor)
        {
            if (IsVersioned(destPath))
            {
                VersionInfo vinfo = GetVersionInfo(destPath, false);
                if (!vinfo.HasLocalChange(VersionStatus.ScheduledDelete) && Directory.Exists(destPath))
                {
                    throw new InvalidOperationException("Cannot move directory. Destination directory already exist.");
                }

                srcPath = srcPath.FullPath;

                // The target directory does not exist, but it is versioned. It may be because
                // it is scheduled to delete, or maybe it has been physicaly deleted. In any
                // case we are going to replace the old directory by the new directory.

                // Revert the old directory, so we can see which files were there so
                // we can delete or replace them
                Revert(destPath, true, monitor);

                // Get the list of files in the directory to be replaced
                ArrayList oldFiles = new ArrayList();
                GetDirectoryFiles(destPath, oldFiles);

                // Get the list of files to move
                ArrayList newFiles = new ArrayList();
                GetDirectoryFiles(srcPath, newFiles);

                // Move all new files to the new destination
                Hashtable copiedFiles   = new Hashtable();
                Hashtable copiedFolders = new Hashtable();
                foreach (string file in newFiles)
                {
                    string src = Path.GetFullPath(file);
                    string dst = Path.Combine(destPath, src.Substring(((string)srcPath).Length + 1));
                    if (File.Exists(dst))
                    {
                        File.Delete(dst);
                    }

                    // Make sure the target directory exists
                    string destDir = Path.GetDirectoryName(dst);
                    if (!Directory.Exists(destDir))
                    {
                        Directory.CreateDirectory(destDir);
                    }

                    // If the source file is versioned, make sure the target directory
                    // is also versioned.
                    if (IsVersioned(src))
                    {
                        MakeDirVersioned(destDir, monitor);
                    }

                    MoveFile(src, dst, true, monitor);
                    copiedFiles [dst] = dst;
                    string df = Path.GetDirectoryName(dst);
                    copiedFolders [df] = df;
                }

                // Delete all old files which have not been replaced
                ArrayList foldersToDelete = new ArrayList();
                foreach (string oldFile in oldFiles)
                {
                    if (!copiedFiles.Contains(oldFile))
                    {
                        DeleteFile(oldFile, true, monitor);
                        string fd = Path.GetDirectoryName(oldFile);
                        if (!copiedFolders.Contains(fd) && !foldersToDelete.Contains(fd))
                        {
                            foldersToDelete.Add(fd);
                        }
                    }
                }

                // Delete old folders
                foreach (string folder in foldersToDelete)
                {
                    Svn.Delete(folder, true, monitor);
                }

                // Delete the source directory
                DeleteDirectory(srcPath, true, monitor);
            }
            else
            {
                if (Directory.Exists(destPath))
                {
                    throw new InvalidOperationException("Cannot move directory. Destination directory already exist.");
                }

                VersionInfo srcInfo = GetVersionInfo(srcPath, false);
                if (srcInfo != null && srcInfo.HasLocalChange(VersionStatus.ScheduledAdd))
                {
                    // If the directory is scheduled to add, cancel it, move the directory, and schedule to add it again
                    MakeDirVersioned(Path.GetDirectoryName(destPath), monitor);
                    Revert(srcPath, true, monitor);
                    base.MoveDirectory(srcPath, destPath, force, monitor);
                    Add(destPath, true, monitor);
                }
                else
                {
                    if (IsVersioned(srcPath))
                    {
                        MakeDirVersioned(Path.GetDirectoryName(destPath), monitor);
                        Svn.Move(srcPath, destPath, force, monitor);
                    }
                    else
                    {
                        base.MoveDirectory(srcPath, destPath, force, monitor);
                    }
                }
            }
        }
Esempio n. 40
0
        public override void Add(FilePath[] paths, bool recurse, IProgressMonitor monitor)
        {
            foreach (FilePath path in paths)
            {
                if (IsVersioned(path) && File.Exists(path) && !Directory.Exists(path))
                {
                    if (rootPath == null)
                    {
                        throw new UserException(GettextCatalog.GetString("Project publishing failed. There is a stale .svn folder in the path '{0}'", path.ParentDirectory));
                    }
                    VersionInfo srcInfo = GetVersionInfo(path, false);
                    if (srcInfo.HasLocalChange(VersionStatus.ScheduledDelete))
                    {
                        // It is a file that was deleted. It can be restored now since it's going
                        // to be added again.
                        // First of all, make a copy of the file
                        string tmp = Path.GetTempFileName();
                        File.Copy(path, tmp, true);

                        // Now revert the status of the file
                        Revert(path, false, monitor);

                        // Copy the file over the old one and clean up
                        File.Copy(tmp, path, true);
                        File.Delete(tmp);
                    }
                }
                else
                {
                    if (!IsVersioned(path.ParentDirectory))
                    {
                        // The file/folder belongs to an unversioned folder. We can add it by versioning the parent
                        // folders up to the root of the repository

                        if (!path.IsChildPathOf(rootPath))
                        {
                            throw new InvalidOperationException("File outside the repository directory");
                        }

                        List <FilePath> dirChain  = new List <FilePath> ();
                        FilePath        parentDir = path.CanonicalPath;
                        do
                        {
                            parentDir = parentDir.ParentDirectory;
                            if (Directory.Exists(SubversionVersionControl.GetDirectoryDotSvn(parentDir)))
                            {
                                break;
                            }
                            dirChain.Add(parentDir);
                        }while (parentDir != rootPath);

                        // Found all parent unversioned dirs. Versin them now.
                        dirChain.Reverse();
                        FileUpdateEventArgs args = new FileUpdateEventArgs();
                        foreach (var d in dirChain)
                        {
                            Svn.Add(d, false, monitor);
                            args.Add(new FileUpdateEventInfo(this, dirChain [0], true));
                        }
                        VersionControlService.NotifyFileStatusChanged(args);
                    }
                    Svn.Add(path, recurse, monitor);
                }
            }
        }
Esempio n. 41
0
 protected override VersionControlOperation GetSupportedOperations(VersionInfo vinfo)
 {
     return(Svn.GetSupportedOperations(this, vinfo, base.GetSupportedOperations(vinfo)));
 }
Esempio n. 42
0
    internal static string ScriptingUrl(System.Type type)
    {
        if (!s_PrefsLoaded)
        {
            LoadPreferences();
        }

        switch (s_DocumentationSource)
        {
        case DocumentationSource.Local:
            return(new System.Uri(
                       Path.Combine(Path.Combine(s_DocumentationPath, VersionInfo.version), VersionInfo.ScriptingUrl(type, false))).AbsoluteUri);

        default:
            return(VersionInfo.ScriptingUrl(type));
        }
    }
Esempio n. 43
0
 private static NotificationSeverity DetermineSeverity(VersionInfo latestVersionInfo)
 {
     return(Enum.Parse <NotificationSeverity>(latestVersionInfo.UpdateSeverity));
 }
Esempio n. 44
0
 public void SetUp()
 {
     _versionInfo = new VersionInfo();
 }
Esempio n. 45
0
    /// <summary>
    ///     Gets the version from the "assembly".
    ///     Should never be null.
    /// </summary>
    public static string GetAssemblyVersion()
    {
        var fvi = VersionInfo.Instance().Version;

        return(fvi.FileVersion.ToString());
    }
Esempio n. 46
0
 /// <remarks/>
 public void GetMetadataAsync(System.Guid modelId, VersionInfo version)
 {
     this.GetMetadataAsync(modelId, version, null);
 }
Esempio n. 47
0
 void OnInfoUpdated(object sender, EventArgs e)
 {
     widget.History = this.info.History;
     vinfo          = this.info.Item.VersionInfo;
 }
Esempio n. 48
0
        public bool LoadPlayerFromDisk(out string error)
        {
            error = string.Empty;
            ZPackage zPackage = LoadPlayerDataFromDisk();
            //backup
            DirectoryInfo dir = Directory.CreateDirectory("backup");

            File.WriteAllBytes($"{dir.FullName}/{m_filename}", zPackage.GetArray());

            if (zPackage == null)
            {
                error = "No player data";
                return(false);
            }

            m_version = zPackage.ReadInt();
            if (!VersionInfo.IsPlayerVersionCompatible(m_version))
            {
                error = "Player data is not compatible, ignoring";
                return(false);
            }

            if (m_version >= 28)
            {
                m_playerStats.m_kills  = zPackage.ReadInt();
                m_playerStats.m_deaths = zPackage.ReadInt();
                m_playerStats.m_crafts = zPackage.ReadInt();
                m_playerStats.m_builds = zPackage.ReadInt();
            }

            int num2 = zPackage.ReadInt();

            for (int i = 0; i < num2; i++)
            {
                long            key             = zPackage.ReadLong();
                WorldPlayerData worldPlayerData = new WorldPlayerData();

                worldPlayerData.m_haveCustomSpawnPoint = zPackage.ReadBool();
                worldPlayerData.m_spawnPoint           = zPackage.ReadVector3();
                worldPlayerData.m_haveLogoutPoint      = zPackage.ReadBool();
                worldPlayerData.m_logoutPoint          = zPackage.ReadVector3();
                if (m_version >= 30)
                {
                    worldPlayerData.m_haveDeathPoint = zPackage.ReadBool();
                    worldPlayerData.m_deathPoint     = zPackage.ReadVector3();
                }
                worldPlayerData.m_homePoint = zPackage.ReadVector3();
                if (m_version >= 29 && zPackage.ReadBool())
                {
                    worldPlayerData.m_mapData = zPackage.ReadByteArray();
                }
                m_worldData.Add(key, worldPlayerData);
            }

            m_playerName = zPackage.ReadString();
            m_playerID   = zPackage.ReadLong();
            m_startSeed  = zPackage.ReadString();

            m_playerData = null;
            if (zPackage.ReadBool())
            {
                m_playerData = zPackage.ReadByteArray();
            }

            return(true);
        }
Esempio n. 49
0
 public Method(string name, VersionInfo version)
 {
     _methodName = name;
     _version    = version;
     _args       = null;
 }
Esempio n. 50
0
        // TODO: This doesn't really belong here, but not sure where to put it
        public static void PopulateWithDefaultHeaderValues(this IMovie movie, string author = null)
        {
            movie.Author          = author ?? Global.Config.DefaultAuthor;
            movie.EmulatorVersion = VersionInfo.GetEmuVersion();
            movie.SystemID        = Global.Emulator.SystemId;

            var settable = new SettingsAdapter(Global.Emulator);

            if (settable.HasSyncSettings)
            {
                movie.SyncSettingsJson = ConfigService.SaveWithType(settable.GetSyncSettings());
            }

            if (Global.Game != null)
            {
                movie.GameName = PathManager.FilesystemSafeName(Global.Game);
                movie.Hash     = Global.Game.Hash;
                if (Global.Game.FirmwareHash != null)
                {
                    movie.FirmwareHash = Global.Game.FirmwareHash;
                }
            }
            else
            {
                movie.GameName = "NULL";
            }

            if (Global.Emulator.HasBoardInfo())
            {
                movie.BoardName = Global.Emulator.AsBoardInfo().BoardName;
            }

            if (Global.Emulator.HasRegions())
            {
                var region = Global.Emulator.AsRegionable().Region;
                if (region == Emulation.Common.DisplayType.PAL)
                {
                    movie.HeaderEntries.Add(HeaderKeys.PAL, "1");
                }
            }

            if (Global.FirmwareManager.RecentlyServed.Any())
            {
                foreach (var firmware in Global.FirmwareManager.RecentlyServed)
                {
                    var key = firmware.SystemId + "_Firmware_" + firmware.FirmwareId;

                    if (!movie.HeaderEntries.ContainsKey(key))
                    {
                        movie.HeaderEntries.Add(key, firmware.Hash);
                    }
                }
            }

            if (Global.Emulator is Gameboy && (Global.Emulator as Gameboy).IsCGBMode())
            {
                movie.HeaderEntries.Add("IsCGBMode", "1");
            }

            if (Global.Emulator is SMS && (Global.Emulator as SMS).IsSG1000)
            {
                movie.HeaderEntries.Add("IsSGMode", "1");
            }

            if (Global.Emulator is GPGX && (Global.Emulator as GPGX).IsSegaCD)
            {
                movie.HeaderEntries.Add("IsSegaCDMode", "1");
            }

            movie.Core = ((CoreAttributes)Attribute
                          .GetCustomAttribute(Global.Emulator.GetType(), typeof(CoreAttributes)))
                         .CoreName;
        }
Esempio n. 51
0
        public LogitechF310LinuxProfile()
        {
            Name = "Logitech F310 Controller";
            Meta = "Logitech F310 Controller on Linux";

            IncludePlatforms = new[] {
                "Linux"
            };

            JoystickNames = new[] {
                "Logitech Gamepad F310"
            };

            MaxUnityVersion = new VersionInfo(4, 9, 0, 0);

            ButtonMappings = new[] {
                new InputControlMapping {
                    Handle = "A",
                    Target = InputControlType.Action1,
                    Source = Button0
                },
                new InputControlMapping {
                    Handle = "B",
                    Target = InputControlType.Action2,
                    Source = Button1
                },
                new InputControlMapping {
                    Handle = "X",
                    Target = InputControlType.Action3,
                    Source = Button2
                },
                new InputControlMapping {
                    Handle = "Y",
                    Target = InputControlType.Action4,
                    Source = Button3
                },
                new InputControlMapping {
                    Handle = "Left Bumper",
                    Target = InputControlType.LeftBumper,
                    Source = Button4
                },
                new InputControlMapping {
                    Handle = "Right Bumper",
                    Target = InputControlType.RightBumper,
                    Source = Button5
                },
                new InputControlMapping {
                    Handle = "Left Stick Button",
                    Target = InputControlType.LeftStickButton,
                    Source = Button9
                },
                new InputControlMapping {
                    Handle = "Right Stick Button",
                    Target = InputControlType.RightStickButton,
                    Source = Button10
                },
                new InputControlMapping {
                    Handle = "Start",
                    Target = InputControlType.Start,
                    Source = Button7
                },
                new InputControlMapping {
                    Handle = "Back",
                    Target = InputControlType.Select,
                    Source = Button6
                }
            };

            AnalogMappings = new[] {
                LeftStickLeftMapping(Analog0),
                LeftStickRightMapping(Analog0),
                LeftStickUpMapping(Analog1),
                LeftStickDownMapping(Analog1),

                RightStickLeftMapping(Analog3),
                RightStickRightMapping(Analog3),
                RightStickUpMapping(Analog4),
                RightStickDownMapping(Analog4),

                DPadLeftMapping(Analog6),
                DPadRightMapping(Analog6),
                DPadUpMapping(Analog7),
                DPadDownMapping(Analog7),

                new InputControlMapping {
                    Handle = "Left Trigger",
                    Target = InputControlType.LeftTrigger,
                    Source = Analog2
                },
                new InputControlMapping {
                    Handle = "Right Trigger",
                    Target = InputControlType.RightTrigger,
                    Source = Analog5
                },
            };
        }
Esempio n. 52
0
        /// <exception cref="Org.Apache.Hadoop.Lib.Server.ServiceException"/>
        protected internal override void Init()
        {
            Log.Info("Using FileSystemAccess JARs version [{}]", VersionInfo.GetVersion());
            string security = GetServiceConfig().Get(AuthenticationType, "simple").Trim();

            if (security.Equals("kerberos"))
            {
                string defaultName = GetServer().GetName();
                string keytab      = Runtime.GetProperty("user.home") + "/" + defaultName + ".keytab";
                keytab = GetServiceConfig().Get(KerberosKeytab, keytab).Trim();
                if (keytab.Length == 0)
                {
                    throw new ServiceException(FileSystemAccessException.ERROR.H01, KerberosKeytab);
                }
                string principal = defaultName + "/localhost@LOCALHOST";
                principal = GetServiceConfig().Get(KerberosPrincipal, principal).Trim();
                if (principal.Length == 0)
                {
                    throw new ServiceException(FileSystemAccessException.ERROR.H01, KerberosPrincipal
                                               );
                }
                Configuration conf = new Configuration();
                conf.Set("hadoop.security.authentication", "kerberos");
                UserGroupInformation.SetConfiguration(conf);
                try
                {
                    UserGroupInformation.LoginUserFromKeytab(principal, keytab);
                }
                catch (IOException ex)
                {
                    throw new ServiceException(FileSystemAccessException.ERROR.H02, ex.Message, ex);
                }
                Log.Info("Using FileSystemAccess Kerberos authentication, principal [{}] keytab [{}]"
                         , principal, keytab);
            }
            else
            {
                if (security.Equals("simple"))
                {
                    Configuration conf = new Configuration();
                    conf.Set("hadoop.security.authentication", "simple");
                    UserGroupInformation.SetConfiguration(conf);
                    Log.Info("Using FileSystemAccess simple/pseudo authentication, principal [{}]", Runtime
                             .GetProperty("user.name"));
                }
                else
                {
                    throw new ServiceException(FileSystemAccessException.ERROR.H09, security);
                }
            }
            string hadoopConfDirProp = GetServiceConfig().Get(HadoopConfDir, GetServer().GetConfigDir
                                                                  ());
            FilePath hadoopConfDir = new FilePath(hadoopConfDirProp).GetAbsoluteFile();

            if (!hadoopConfDir.Exists())
            {
                hadoopConfDir = new FilePath(GetServer().GetConfigDir()).GetAbsoluteFile();
            }
            if (!hadoopConfDir.Exists())
            {
                throw new ServiceException(FileSystemAccessException.ERROR.H10, hadoopConfDir);
            }
            try
            {
                serviceHadoopConf = LoadHadoopConf(hadoopConfDir);
            }
            catch (IOException ex)
            {
                throw new ServiceException(FileSystemAccessException.ERROR.H11, ex.ToString(), ex
                                           );
            }
            Log.Debug("FileSystemAccess FileSystem configuration:");
            foreach (DictionaryEntry entry in serviceHadoopConf)
            {
                Log.Debug("  {} = {}", entry.Key, entry.Value);
            }
            SetRequiredServiceHadoopConf(serviceHadoopConf);
            nameNodeWhitelist = ToLowerCase(GetServiceConfig().GetTrimmedStringCollection(NameNodeWhitelist
                                                                                          ));
        }
Esempio n. 53
0
    public IEnumerator CheckUpdate(string downloadPath)
    {
        while (!ConfigLoaded)
        {
            yield return(null);
        }

        var downloadPathStr = BMUtility.InterpretPath(downloadPath, curPlatform);

        if (string.IsNullOrEmpty(downloadPathStr))
        {
            CheckUpdateError = "{BM} Invalid update download path" + downloadPathStr;
            yield break;
        }

        remoteRootUrl = new Uri(downloadPathStr).AbsoluteUri;

        //Try to get Url redirect file
        var redirectUrl = formatUrl(remoteRootUrl, "BMRedirect.txt");

        if (!string.IsNullOrEmpty(redirectUrl))
        {
            WWW redirectWWW = new WWW(redirectUrl);
            yield return(redirectWWW);

            if (redirectWWW.error == null)
            {
                //Redirect download
                var redirectedDownloadPath = redirectWWW.text;
                downloadPathStr = BMUtility.InterpretPath(redirectedDownloadPath, curPlatform);
                if (string.IsNullOrEmpty(downloadPathStr))
                {
                    Debug.LogError("{BM} Invalid redirected download Path :" + downloadPathStr + "(Retrived from url:" + redirectUrl + ")." +
                                   "Using the original download path" + remoteRootUrl);
                }
                else
                {
                    remoteRootUrl = new Uri(downloadPathStr).AbsoluteUri;
                }
            }
            redirectWWW.Dispose();
        }

        var versionInfo = new VersionInfo(remoteRootUrl);

        yield return(StartCoroutine(downloadVersionInfoCo(versionInfo)));

        CheckUpdateError = versionInfo.error;

        if (versionInfo.isValue)
        {
            UpdateTotalSize = 0;
            UpdateVersion   = versionInfo.listVersion;

            mergeVersion(versionInfo);
            refreshBundleDict();
        }

        updateList = new List <BundleDownloadInfo>();
        foreach (var bundleDownloadInfo in bundles)
        {
            if (bundleDownloadInfo.needDownload)
            {
                if (!updateList.Contains(bundleDownloadInfo))
                {
                    updateList.Add(bundleDownloadInfo);
                    UpdateTotalSize += bundleDownloadInfo.versionInfo.size;
                }
            }
        }
    }
Esempio n. 54
0
 /// <summary>
 /// Load the data for the Version Info tab.
 /// </summary>
 private void LoadPageVersionInfo()
 {
     // Get Version, database info and executing assembly location
     lRockVersion.Text   = string.Format("{0} <small>({1})</small>", VersionInfo.GetRockProductVersionFullName(), VersionInfo.GetRockProductVersionNumber());
     lClientCulture.Text = System.Globalization.CultureInfo.CurrentCulture.ToString();
 }
Esempio n. 55
0
        public static async Task <int> MainAsync(IConfiguration configuration)
        {
            // Bring up the logger before anything else so we can log errors ASAP
            ILogger logger = SetupLogger(configuration);

            logger.LogInformation("Initializing Edge Agent.");

            VersionInfo versionInfo = VersionInfo.Get(VersionInfoFileName);

            if (versionInfo != VersionInfo.Empty)
            {
                logger.LogInformation($"Version - {versionInfo.ToString(true)}");
            }

            LogLogo(logger);

            string mode;

            string                      configSourceConfig;
            string                      backupConfigFilePath;
            int                         maxRestartCount;
            TimeSpan                    intensiveCareTime;
            int                         coolOffTimeUnitInSeconds;
            bool                        usePersistentStorage;
            string                      storagePath;
            bool                        enableNonPersistentStorageBackup;
            Option <string>             storageBackupPath = Option.None <string>();
            string                      edgeDeviceHostName;
            string                      dockerLoggingDriver;
            Dictionary <string, string> dockerLoggingOptions;
            IEnumerable <global::Docker.DotNet.Models.AuthConfig> dockerAuthConfig;
            int           configRefreshFrequencySecs;
            MetricsConfig metricsConfig;

            try
            {
                mode = configuration.GetValue(Constants.ModeKey, "docker");
                configSourceConfig       = configuration.GetValue <string>("ConfigSource");
                backupConfigFilePath     = configuration.GetValue <string>("BackupConfigFilePath");
                maxRestartCount          = configuration.GetValue <int>("MaxRestartCount");
                intensiveCareTime        = TimeSpan.FromMinutes(configuration.GetValue <int>("IntensiveCareTimeInMinutes"));
                coolOffTimeUnitInSeconds = configuration.GetValue("CoolOffTimeUnitInSeconds", 10);
                usePersistentStorage     = configuration.GetValue("UsePersistentStorage", true);

                // Note: Keep in sync with iotedge-check's edge-agent-storage-mounted-from-host check (edgelet/iotedge/src/check/checks/storage_mounted_from_host.rs)
                storagePath = GetOrCreateDirectoryPath(configuration.GetValue <string>("StorageFolder"), EdgeAgentStorageFolder);
                enableNonPersistentStorageBackup = configuration.GetValue("EnableNonPersistentStorageBackup", false);

                if (enableNonPersistentStorageBackup)
                {
                    storageBackupPath = Option.Some(GetOrCreateDirectoryPath(configuration.GetValue <string>("BackupFolder"), EdgeAgentStorageBackupFolder));
                }

                edgeDeviceHostName         = configuration.GetValue <string>(Constants.EdgeDeviceHostNameKey);
                dockerLoggingDriver        = configuration.GetValue <string>("DockerLoggingDriver");
                dockerLoggingOptions       = configuration.GetSection("DockerLoggingOptions").Get <Dictionary <string, string> >() ?? new Dictionary <string, string>();
                dockerAuthConfig           = configuration.GetSection("DockerRegistryAuth").Get <List <global::Docker.DotNet.Models.AuthConfig> >() ?? new List <global::Docker.DotNet.Models.AuthConfig>();
                configRefreshFrequencySecs = configuration.GetValue("ConfigRefreshFrequencySecs", 3600);
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error reading the Agent's configuration.");
                return(1);
            }

            IContainer container;

            try
            {
                var builder = new ContainerBuilder();
                builder.RegisterModule(new LoggingModule(dockerLoggingDriver, dockerLoggingOptions));
                string productInfo = versionInfo != VersionInfo.Empty ? $"{Constants.IoTEdgeAgentProductInfoIdentifier}/{versionInfo}" : Constants.IoTEdgeAgentProductInfoIdentifier;
                Option <UpstreamProtocol> upstreamProtocol = configuration.GetValue <string>(Constants.UpstreamProtocolKey).ToUpstreamProtocol();
                Option <IWebProxy>        proxy            = Proxy.Parse(configuration.GetValue <string>("https_proxy"), logger);
                bool                 closeOnIdleTimeout    = configuration.GetValue(Constants.CloseOnIdleTimeout, false);
                int                  idleTimeoutSecs       = configuration.GetValue(Constants.IdleTimeoutSecs, 300);
                TimeSpan             idleTimeout           = TimeSpan.FromSeconds(idleTimeoutSecs);
                ExperimentalFeatures experimentalFeatures  = ExperimentalFeatures.Create(configuration.GetSection("experimentalFeatures"), logger);
                metricsConfig = new MetricsConfig(experimentalFeatures.EnableMetrics, MetricsListenerConfig.Create(configuration));
                string iothubHostname;
                string deviceId;

                switch (mode.ToLowerInvariant())
                {
                case Constants.DockerMode:
                    var    dockerUri = new Uri(configuration.GetValue <string>("DockerUri"));
                    string deviceConnectionString = configuration.GetValue <string>("DeviceConnectionString");
                    IotHubConnectionStringBuilder connectionStringParser = IotHubConnectionStringBuilder.Create(deviceConnectionString);
                    deviceId       = connectionStringParser.DeviceId;
                    iothubHostname = connectionStringParser.HostName;
                    builder.RegisterInstance(metricsConfig.Enabled
                                 ? new MetricsProvider("edgeagent", iothubHostname, deviceId)
                                 : new NullMetricsProvider() as IMetricsProvider);
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, enableNonPersistentStorageBackup, storageBackupPath));
                    builder.RegisterModule(new DockerModule(deviceConnectionString, edgeDeviceHostName, dockerUri, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout));
                    break;

                case Constants.IotedgedMode:
                    string managementUri = configuration.GetValue <string>(Constants.EdgeletManagementUriVariableName);
                    string workloadUri   = configuration.GetValue <string>(Constants.EdgeletWorkloadUriVariableName);
                    iothubHostname = configuration.GetValue <string>(Constants.IotHubHostnameVariableName);
                    deviceId       = configuration.GetValue <string>(Constants.DeviceIdVariableName);
                    string moduleId           = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdentityName);
                    string moduleGenerationId = configuration.GetValue <string>(Constants.EdgeletModuleGenerationIdVariableName);
                    string apiVersion         = configuration.GetValue <string>(Constants.EdgeletApiVersionVariableName);
                    builder.RegisterInstance(metricsConfig.Enabled
                                 ? new MetricsProvider("edgeagent", iothubHostname, deviceId)
                                 : new NullMetricsProvider() as IMetricsProvider);
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), Option.Some(apiVersion), moduleId, Option.Some(moduleGenerationId), enableNonPersistentStorageBackup, storageBackupPath));
                    builder.RegisterModule(new EdgeletModule(iothubHostname, edgeDeviceHostName, deviceId, new Uri(managementUri), new Uri(workloadUri), apiVersion, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout));
                    break;

                case Constants.KubernetesMode:
                    managementUri      = configuration.GetValue <string>(Constants.EdgeletManagementUriVariableName);
                    workloadUri        = configuration.GetValue <string>(Constants.EdgeletWorkloadUriVariableName);
                    moduleId           = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdentityName);
                    moduleGenerationId = configuration.GetValue <string>(Constants.EdgeletModuleGenerationIdVariableName);
                    apiVersion         = configuration.GetValue <string>(Constants.EdgeletApiVersionVariableName);
                    iothubHostname     = configuration.GetValue <string>(Constants.IotHubHostnameVariableName);
                    deviceId           = configuration.GetValue <string>(Constants.DeviceIdVariableName);
                    string             proxyImage = configuration.GetValue <string>(K8sConstants.ProxyImageEnvKey);
                    Option <string>    proxyImagePullSecretName      = Option.Maybe(configuration.GetValue <string>(K8sConstants.ProxyImagePullSecretNameEnvKey));
                    string             proxyConfigPath               = configuration.GetValue <string>(K8sConstants.ProxyConfigPathEnvKey);
                    string             proxyConfigVolumeName         = configuration.GetValue <string>(K8sConstants.ProxyConfigVolumeEnvKey);
                    string             proxyConfigMapName            = configuration.GetValue <string>(K8sConstants.ProxyConfigMapNameEnvKey);
                    string             proxyTrustBundlePath          = configuration.GetValue <string>(K8sConstants.ProxyTrustBundlePathEnvKey);
                    string             proxyTrustBundleVolumeName    = configuration.GetValue <string>(K8sConstants.ProxyTrustBundleVolumeEnvKey);
                    string             proxyTrustBundleConfigMapName = configuration.GetValue <string>(K8sConstants.ProxyTrustBundleConfigMapEnvKey);
                    PortMapServiceType mappedServiceDefault          = GetDefaultServiceType(configuration);
                    bool          enableServiceCallTracing           = configuration.GetValue <bool>(K8sConstants.EnableK8sServiceCallTracingName);
                    string        persistentVolumeName               = configuration.GetValue <string>(K8sConstants.PersistentVolumeNameKey);
                    string        storageClassName = configuration.GetValue <string>(K8sConstants.StorageClassNameKey);
                    Option <uint> persistentVolumeClaimDefaultSizeMb = Option.Maybe(configuration.GetValue <uint?>(K8sConstants.PersistentVolumeClaimDefaultSizeInMbKey));
                    string        deviceNamespace = configuration.GetValue <string>(K8sConstants.K8sNamespaceKey);
                    var           kubernetesExperimentalFeatures = KubernetesExperimentalFeatures.Create(configuration.GetSection("experimentalFeatures"), logger);
                    var           moduleOwner = new KubernetesModuleOwner(
                        configuration.GetValue <string>(K8sConstants.EdgeK8sObjectOwnerApiVersionKey),
                        configuration.GetValue <string>(K8sConstants.EdgeK8sObjectOwnerKindKey),
                        configuration.GetValue <string>(K8sConstants.EdgeK8sObjectOwnerNameKey),
                        configuration.GetValue <string>(K8sConstants.EdgeK8sObjectOwnerUidKey));
                    bool runAsNonRoot = configuration.GetValue <bool>(K8sConstants.RunAsNonRootKey);

                    builder.RegisterInstance(metricsConfig.Enabled
                                 ? new MetricsProvider("edgeagent", iothubHostname, deviceId)
                                 : new NullMetricsProvider() as IMetricsProvider);
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), Option.Some(apiVersion), moduleId, Option.Some(moduleGenerationId), enableNonPersistentStorageBackup, storageBackupPath));
                    builder.RegisterModule(new KubernetesModule(
                                               iothubHostname,
                                               deviceId,
                                               edgeDeviceHostName,
                                               proxyImage,
                                               proxyImagePullSecretName,
                                               proxyConfigPath,
                                               proxyConfigVolumeName,
                                               proxyConfigMapName,
                                               proxyTrustBundlePath,
                                               proxyTrustBundleVolumeName,
                                               proxyTrustBundleConfigMapName,
                                               apiVersion,
                                               deviceNamespace,
                                               new Uri(managementUri),
                                               new Uri(workloadUri),
                                               dockerAuthConfig,
                                               upstreamProtocol,
                                               Option.Some(productInfo),
                                               mappedServiceDefault,
                                               enableServiceCallTracing,
                                               persistentVolumeName,
                                               storageClassName,
                                               persistentVolumeClaimDefaultSizeMb,
                                               proxy,
                                               closeOnIdleTimeout,
                                               idleTimeout,
                                               kubernetesExperimentalFeatures,
                                               moduleOwner,
                                               runAsNonRoot));

                    break;

                default:
                    throw new InvalidOperationException($"Mode '{mode}' not supported.");
                }

                switch (configSourceConfig.ToLowerInvariant())
                {
                case "twin":
                    bool enableStreams      = configuration.GetValue(Constants.EnableStreams, false);
                    int  requestTimeoutSecs = configuration.GetValue(Constants.RequestTimeoutSecs, 600);
                    builder.RegisterModule(
                        new TwinConfigSourceModule(
                            iothubHostname,
                            deviceId,
                            backupConfigFilePath,
                            configuration,
                            versionInfo,
                            TimeSpan.FromSeconds(configRefreshFrequencySecs),
                            enableStreams,
                            TimeSpan.FromSeconds(requestTimeoutSecs),
                            experimentalFeatures));
                    break;

                case "local":
                    string localConfigFilePath = GetLocalConfigFilePath(configuration, logger);
                    builder.RegisterModule(new FileConfigSourceModule(localConfigFilePath, configuration));
                    break;

                default:
                    throw new InvalidOperationException($"ConfigSource '{configSourceConfig}' not supported.");
                }

                container = builder.Build();
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error building application.");
                return(1);
            }

            // Initialize metrics
            var metricsLifetimes = new List <IDisposable>();

            if (metricsConfig.Enabled)
            {
                var metricsListener = new MetricsListener(metricsConfig.ListenerConfig, container.Resolve <IMetricsProvider>());
                metricsListener.Start(logger);
                metricsLifetimes.Add(metricsListener);
            }

            Dictionary <Type, string> recognizedExceptions = new Dictionary <Type, string>
            {
                // TODO: Decide what exceptions to recognize and ignore
                { typeof(Newtonsoft.Json.JsonSerializationException), "json_serialization" },
                { typeof(ArgumentException), "argument" },
                { typeof(Rest.HttpOperationException), "http" },
            };
            HashSet <Type> ignoredExceptions = new HashSet <Type>
            {
                typeof(TaskCanceledException),
                typeof(OperationCanceledException),
            };

            metricsLifetimes.Add(new ExceptionCounter(recognizedExceptions, ignoredExceptions, container.Resolve <IMetricsProvider>()));

            // TODO move this code to Agent
            if (mode.ToLowerInvariant().Equals(Constants.KubernetesMode))
            {
                // Start environment operator
                IKubernetesEnvironmentOperator environmentOperator = container.Resolve <IKubernetesEnvironmentOperator>();
                environmentOperator.Start();

                // Start the edge deployment operator
                IEdgeDeploymentOperator edgeDeploymentOperator = container.Resolve <IEdgeDeploymentOperator>();
                edgeDeploymentOperator.Start();
            }

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler)
                = ShutdownHandler.Init(ShutdownWaitPeriod, logger);

            // Register request handlers
            await RegisterRequestHandlers(container);

            // Initialize stream request listener
            IStreamRequestListener streamRequestListener = await container.Resolve <Task <IStreamRequestListener> >();

            streamRequestListener.InitPump();

            int returnCode;

            using (IConfigSource unused = await container.Resolve <Task <IConfigSource> >())
            {
                Option <Agent> agentOption = Option.None <Agent>();

                try
                {
                    Agent agent = await container.Resolve <Task <Agent> >();

                    agentOption = Option.Some(agent);
                    while (!cts.Token.IsCancellationRequested)
                    {
                        try
                        {
                            await agent.ReconcileAsync(cts.Token).TimeoutAfter(ReconcileTimeout);
                        }
                        catch (Exception ex) when(!ex.IsFatal())
                        {
                            logger.LogWarning(AgentEventIds.Agent, ex, "Agent reconcile concluded with errors.");
                        }

                        await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);
                    }

                    logger.LogInformation("Closing module management agent.");

                    returnCode = 0;
                }
                catch (OperationCanceledException)
                {
                    logger.LogInformation("Main thread terminated");
                    returnCode = 0;
                }
                catch (Exception ex)
                {
                    logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error starting Agent.");
                    returnCode = 1;
                }

                metricsLifetimes.ForEach(m => m.Dispose());
                // Attempt to report shutdown of Agent
                await Cleanup(agentOption, logger);
                await CloseDbStoreProviderAsync(container);

                completed.Set();
            }

            handler.ForEach(h => GC.KeepAlive(h));
            return(returnCode);
        }
Esempio n. 56
0
        public static async Task <int> MainAsync(IConfiguration configuration)
        {
            // Bring up the logger before anything else so we can log errors ASAP
            ILogger logger = SetupLogger(configuration);

            logger.LogInformation("Initializing Edge Agent.");

            VersionInfo versionInfo = VersionInfo.Get(VersionInfoFileName);

            if (versionInfo != VersionInfo.Empty)
            {
                logger.LogInformation($"Version - {versionInfo.ToString(true)}");
            }

            LogLogo(logger);

            string mode;

            string                      configSourceConfig;
            string                      backupConfigFilePath;
            int                         maxRestartCount;
            TimeSpan                    intensiveCareTime;
            int                         coolOffTimeUnitInSeconds;
            bool                        usePersistentStorage;
            string                      storagePath;
            bool                        enableNonPersistentStorageBackup;
            Option <string>             storageBackupPath = Option.None <string>();
            string                      edgeDeviceHostName;
            string                      dockerLoggingDriver;
            Dictionary <string, string> dockerLoggingOptions;
            IEnumerable <global::Docker.DotNet.Models.AuthConfig> dockerAuthConfig;
            int configRefreshFrequencySecs;
            ExperimentalFeatures experimentalFeatures;
            MetricsConfig        metricsConfig;
            DiagnosticConfig     diagnosticConfig;
            bool useServerHeartbeat;

            try
            {
                mode = configuration.GetValue(Constants.ModeKey, "docker");
                configSourceConfig       = configuration.GetValue <string>("ConfigSource");
                backupConfigFilePath     = configuration.GetValue <string>("BackupConfigFilePath");
                maxRestartCount          = configuration.GetValue <int>("MaxRestartCount");
                intensiveCareTime        = TimeSpan.FromMinutes(configuration.GetValue <int>("IntensiveCareTimeInMinutes"));
                coolOffTimeUnitInSeconds = configuration.GetValue("CoolOffTimeUnitInSeconds", 10);
                usePersistentStorage     = configuration.GetValue("UsePersistentStorage", true);
                useServerHeartbeat       = configuration.GetValue("UseServerHeartbeat", true);

                // Note: Keep in sync with iotedge-check's edge-agent-storage-mounted-from-host check (edgelet/iotedge/src/check/checks/storage_mounted_from_host.rs)
                storagePath = GetOrCreateDirectoryPath(configuration.GetValue <string>("StorageFolder"), EdgeAgentStorageFolder);
                enableNonPersistentStorageBackup = configuration.GetValue("EnableNonPersistentStorageBackup", false);

                if (enableNonPersistentStorageBackup)
                {
                    storageBackupPath = Option.Some(GetOrCreateDirectoryPath(configuration.GetValue <string>("BackupFolder"), EdgeAgentStorageBackupFolder));
                }

                backupConfigFilePath = GetFullBackupFilePath(storagePath, backupConfigFilePath);

                edgeDeviceHostName   = configuration.GetValue <string>(Constants.EdgeDeviceHostNameKey);
                dockerLoggingDriver  = configuration.GetValue <string>("DockerLoggingDriver");
                dockerLoggingOptions = configuration.GetSection("DockerLoggingOptions").Get <Dictionary <string, string> >() ?? new Dictionary <string, string>();
                dockerAuthConfig     = configuration.GetSection("DockerRegistryAuth").Get <List <global::Docker.DotNet.Models.AuthConfig> >() ?? new List <global::Docker.DotNet.Models.AuthConfig>();

                NestedEdgeParentUriParser parser = new NestedEdgeParentUriParser();
                dockerAuthConfig = dockerAuthConfig.Select(c =>
                {
                    c.Password = parser.ParseURI(c.Password).GetOrElse(c.Password);
                    return(c);
                })
                                   .ToList();

                configRefreshFrequencySecs = configuration.GetValue("ConfigRefreshFrequencySecs", 3600);
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error reading the Agent's configuration.");
                return(1);
            }

            IContainer container;

            try
            {
                var builder = new ContainerBuilder();
                builder.RegisterModule(new LoggingModule(dockerLoggingDriver, dockerLoggingOptions));
                string productInfo =
                    versionInfo != VersionInfo.Empty ?
                    $"{Constants.IoTEdgeAgentProductInfoIdentifier}/{versionInfo}" :
                    Constants.IoTEdgeAgentProductInfoIdentifier;
                Option <UpstreamProtocol> upstreamProtocol = configuration.GetValue <string>(Constants.UpstreamProtocolKey).ToUpstreamProtocol();
                Option <IWebProxy>        proxy            = Proxy.Parse(configuration.GetValue <string>("https_proxy"), logger);
                bool     closeOnIdleTimeout = configuration.GetValue(Constants.CloseOnIdleTimeout, false);
                int      idleTimeoutSecs    = configuration.GetValue(Constants.IdleTimeoutSecs, 300);
                TimeSpan idleTimeout        = TimeSpan.FromSeconds(idleTimeoutSecs);
                experimentalFeatures = ExperimentalFeatures.Create(configuration.GetSection("experimentalFeatures"), logger);
                Option <ulong>           storageTotalMaxWalSize     = GetConfigIfExists <ulong>(Constants.StorageMaxTotalWalSize, configuration, logger);
                Option <ulong>           storageMaxManifestFileSize = GetConfigIfExists <ulong>(Constants.StorageMaxManifestFileSize, configuration, logger);
                Option <int>             storageMaxOpenFiles        = GetConfigIfExists <int>(Constants.StorageMaxOpenFiles, configuration, logger);
                Option <StorageLogLevel> storageLogLevel            = GetConfigIfExists <StorageLogLevel>(Constants.StorageLogLevel, configuration, logger);
                string iothubHostname;
                string deviceId;
                string apiVersion = "2018-06-28";
                Option <X509Certificate2> manifestTrustBundle = Option.None <X509Certificate2>();

                switch (mode.ToLowerInvariant())
                {
                case Constants.DockerMode:
                    var    dockerUri = new Uri(configuration.GetValue <string>("DockerUri"));
                    string deviceConnectionString = configuration.GetValue <string>("DeviceConnectionString");
                    IotHubConnectionStringBuilder connectionStringParser = IotHubConnectionStringBuilder.Create(deviceConnectionString);
                    deviceId       = connectionStringParser.DeviceId;
                    iothubHostname = connectionStringParser.HostName;
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, enableNonPersistentStorageBackup, storageBackupPath, storageTotalMaxWalSize, storageMaxManifestFileSize, storageMaxOpenFiles, storageLogLevel));
                    builder.RegisterModule(new DockerModule(deviceConnectionString, edgeDeviceHostName, dockerUri, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout, useServerHeartbeat, backupConfigFilePath));
                    break;

                case Constants.IotedgedMode:
                    string managementUri = configuration.GetValue <string>(Constants.EdgeletManagementUriVariableName);
                    string workloadUri   = configuration.GetValue <string>(Constants.EdgeletWorkloadUriVariableName);
                    bool   checkImagePullBeforeModuleCreate = configuration.GetValue <bool>(Constants.CheckImagePullBeforeModuleCreate, true);
                    iothubHostname = configuration.GetValue <string>(Constants.IotHubHostnameVariableName);
                    deviceId       = configuration.GetValue <string>(Constants.DeviceIdVariableName);
                    string moduleId           = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdentityName);
                    string moduleGenerationId = configuration.GetValue <string>(Constants.EdgeletModuleGenerationIdVariableName);
                    apiVersion = configuration.GetValue <string>(Constants.EdgeletApiVersionVariableName);
                    TimeSpan performanceMetricsUpdateFrequency = configuration.GetTimeSpan("PerformanceMetricsUpdateFrequency", TimeSpan.FromMinutes(5));
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), Option.Some(apiVersion), moduleId, Option.Some(moduleGenerationId), enableNonPersistentStorageBackup, storageBackupPath, storageTotalMaxWalSize, storageMaxManifestFileSize, storageMaxOpenFiles, storageLogLevel));
                    builder.RegisterModule(new EdgeletModule(iothubHostname, deviceId, new Uri(managementUri), new Uri(workloadUri), apiVersion, dockerAuthConfig, upstreamProtocol, proxy, productInfo, closeOnIdleTimeout, idleTimeout, performanceMetricsUpdateFrequency, useServerHeartbeat, backupConfigFilePath, checkImagePullBeforeModuleCreate));
                    IEnumerable <X509Certificate2> trustBundle =
                        await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(workloadUri), apiVersion, Constants.WorkloadApiVersion, moduleId, moduleGenerationId);

                    CertificateHelper.InstallCertificates(trustBundle, logger);
                    manifestTrustBundle = await CertificateHelper.GetManifestTrustBundleFromEdgelet(new Uri(workloadUri), apiVersion, Constants.WorkloadApiVersion, moduleId, moduleGenerationId);

                    break;

                case Constants.KubernetesMode:
                default:
                    throw new InvalidOperationException($"Mode '{mode}' not supported.");
                }

                switch (configSourceConfig.ToLowerInvariant())
                {
                case "twin":
                    bool enableStreams      = configuration.GetValue(Constants.EnableStreams, false);
                    int  requestTimeoutSecs = configuration.GetValue(Constants.RequestTimeoutSecs, 600);
                    builder.RegisterModule(
                        new TwinConfigSourceModule(
                            iothubHostname,
                            deviceId,
                            configuration,
                            versionInfo,
                            TimeSpan.FromSeconds(configRefreshFrequencySecs),
                            enableStreams,
                            TimeSpan.FromSeconds(requestTimeoutSecs),
                            experimentalFeatures,
                            manifestTrustBundle));
                    break;

                case "local":
                    string localConfigFilePath = GetLocalConfigFilePath(configuration, logger);
                    builder.RegisterModule(new FileConfigSourceModule(localConfigFilePath, configuration, versionInfo));
                    break;

                default:
                    throw new InvalidOperationException($"ConfigSource '{configSourceConfig}' not supported.");
                }

                metricsConfig = new MetricsConfig(configuration);
                builder.RegisterModule(new MetricsModule(metricsConfig, iothubHostname, deviceId));

                bool diagnosticsEnabled = configuration.GetValue("SendRuntimeQualityTelemetry", true);
                diagnosticConfig = new DiagnosticConfig(diagnosticsEnabled, storagePath, configuration);
                builder.RegisterModule(new DiagnosticsModule(diagnosticConfig));

                container = builder.Build();
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error building application.");
                return(1);
            }

            // Initialize metrics
            if (metricsConfig.Enabled)
            {
                container.Resolve <IMetricsListener>().Start(logger);
                container.Resolve <ISystemResourcesMetrics>().Start(logger);
                await container.Resolve <MetadataMetrics>().Start(logger, versionInfo.ToString(true), Newtonsoft.Json.JsonConvert.SerializeObject(experimentalFeatures));
            }

            // Initialize metric uploading
            if (diagnosticConfig.Enabled)
            {
                MetricsWorker worker = await container.Resolve <Task <MetricsWorker> >();

                worker.Start(diagnosticConfig.ScrapeInterval, diagnosticConfig.UploadInterval);
                Console.WriteLine($"Scraping frequency: {diagnosticConfig.ScrapeInterval}\nUpload Frequency: {diagnosticConfig.UploadInterval}");
            }

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler)
                = ShutdownHandler.Init(ShutdownWaitPeriod, logger);

            // Register request handlers
            await RegisterRequestHandlers(container);

            // Initialize stream request listener
            IStreamRequestListener streamRequestListener = await container.Resolve <Task <IStreamRequestListener> >();

            streamRequestListener.InitPump();

            int returnCode;

            using (IConfigSource unused = await container.Resolve <Task <IConfigSource> >())
            {
                Option <Agent> agentOption = Option.None <Agent>();

                try
                {
                    Agent agent = await container.Resolve <Task <Agent> >();

                    agentOption = Option.Some(agent);
                    while (!cts.Token.IsCancellationRequested)
                    {
                        try
                        {
                            await agent.ReconcileAsync(cts.Token).TimeoutAfter(ReconcileTimeout);
                        }
                        catch (Exception ex) when(!ex.IsFatal())
                        {
                            logger.LogWarning(AgentEventIds.Agent, ex, "Agent reconcile concluded with errors.");
                        }

                        await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);
                    }

                    logger.LogInformation("Closing module management agent.");

                    returnCode = 0;
                }
                catch (OperationCanceledException)
                {
                    logger.LogInformation("Main thread terminated");
                    returnCode = 0;
                }
                catch (Exception ex)
                {
                    logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error starting Agent.");
                    returnCode = 1;
                }

                // Attempt to report shutdown of Agent
                await Cleanup(agentOption, logger);
                await CloseDbStoreProviderAsync(container);

                if (metricsConfig.Enabled && returnCode == 0)
                {
                    container.Resolve <IDeploymentMetrics>().IndicateCleanShutdown();
                }

                completed.Set();
            }

            handler.ForEach(h => GC.KeepAlive(h));
            return(returnCode);
        }
Esempio n. 57
0
        internal unsafe int GetModuleVersionInformation(
            IntPtr self,
            uint index,
            ulong baseAddress,
            [MarshalAs(UnmanagedType.LPStr)] string item,
            byte *buffer,
            uint bufferSize,
            uint *verInfoSize)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(verInfoSize == null);

            uint i = 0;

            foreach (ModuleInfo module in DataReader.EnumerateModules())
            {
                if ((index != uint.MaxValue && i == index) || (index == uint.MaxValue && baseAddress == module.ImageBase))
                {
                    if (item == "\\")
                    {
                        uint versionSize = (uint)Marshal.SizeOf(typeof(VS_FIXEDFILEINFO));
                        Write(verInfoSize, versionSize);
                        if (bufferSize < versionSize)
                        {
                            return(E_INVALIDARG);
                        }
                        VS_FIXEDFILEINFO *fileInfo = (VS_FIXEDFILEINFO *)buffer;
                        fileInfo->dwSignature     = 0;
                        fileInfo->dwStrucVersion  = 0;
                        fileInfo->dwFileFlagsMask = 0;
                        fileInfo->dwFileFlags     = 0;

                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            VersionInfo versionInfo = module.Version;
                            fileInfo->dwFileVersionMS = (uint)versionInfo.Minor | (uint)versionInfo.Major << 16;
                            fileInfo->dwFileVersionLS = (uint)versionInfo.Patch | (uint)versionInfo.Revision << 16;
                            return(S_OK);
                        }
                        else
                        {
                            if (SearchVersionString(module, out string versionString))
                            {
                                int spaceIndex = versionString.IndexOf(' ');
                                if (spaceIndex > 0)
                                {
                                    if (versionString[spaceIndex - 1] == '.')
                                    {
                                        spaceIndex--;
                                    }
                                    string versionToParse = versionString.Substring(0, spaceIndex);
                                    try
                                    {
                                        Version versionInfo = Version.Parse(versionToParse);
                                        fileInfo->dwFileVersionMS = (uint)versionInfo.Minor | (uint)versionInfo.Major << 16;
                                        fileInfo->dwFileVersionLS = (uint)versionInfo.Revision | (uint)versionInfo.Build << 16;
                                        return(S_OK);
                                    }
                                    catch (ArgumentException ex)
                                    {
                                        Trace.TraceError($"GetModuleVersion FAILURE: '{versionToParse}' '{versionString}' {ex.ToString()}");
                                    }
                                }
                            }
                            break;
                        }
                    }
                    else if (item == "\\StringFileInfo\\040904B0\\FileVersion")
                    {
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            return(E_INVALIDARG);
                        }
                        else
                        {
                            if (SearchVersionString(module, out string versionString))
                            {
                                byte[] source = Encoding.ASCII.GetBytes(versionString + '\0');
                                Marshal.Copy(source, 0, new IntPtr(buffer), Math.Min(source.Length, (int)bufferSize));
                                return(S_OK);
                            }
                            break;
                        }
                    }
                    else
                    {
                        return(E_INVALIDARG);
                    }
                }
                i++;
            }

            return(E_FAIL);
        }
Esempio n. 58
0
 /// <summary>
 /// Fetches and displays the official Rock product version.
 /// </summary>
 protected void DisplayRockVersion()
 {
     lRockVersion.Text     = string.Format("<b>Current Version: </b> {0}", VersionInfo.GetRockProductVersionFullName());
     lNoUpdateVersion.Text = VersionInfo.GetRockProductVersionFullName();
 }
Esempio n. 59
0
        public async Task TestEdgeHubConnection()
        {
            const string EdgeDeviceId                   = "testHubEdgeDevice1";
            var          twinMessageConverter           = new TwinMessageConverter();
            var          twinCollectionMessageConverter = new TwinCollectionMessageConverter();
            var          messageConverterProvider       = new MessageConverterProvider(
                new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Client.Message), new DeviceClientMessageConverter() },
                { typeof(Twin), twinMessageConverter },
                { typeof(TwinCollection), twinCollectionMessageConverter }
            });

            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            Devices.IotHubConnectionStringBuilder iotHubConnectionStringBuilder = Devices.IotHubConnectionStringBuilder.Create(iotHubConnectionString);
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            await registryManager.OpenAsync();

            string iothubHostName   = iotHubConnectionStringBuilder.HostName;
            var    identityProvider = new IdentityProvider(iothubHostName);
            var    identityFactory  = new ClientCredentialsFactory(identityProvider);

            (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(EdgeDeviceId, iotHubConnectionString, registryManager, true, false);

            string edgeHubConnectionString = $"{deviceConnStr};ModuleId={EdgeHubModuleId}";

            IClientCredentials edgeHubCredentials = identityFactory.GetWithConnectionString(edgeHubConnectionString);
            string             sasKey             = ConnectionStringHelper.GetSharedAccessKey(deviceConnStr);
            var signatureProvider       = new SharedAccessKeySignatureProvider(sasKey);
            var credentialsCache        = Mock.Of <ICredentialsCache>();
            var cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                new ClientProvider(),
                Option.None <UpstreamProtocol>(),
                new ClientTokenProvider(signatureProvider, iothubHostName, edgeDeviceId, TimeSpan.FromMinutes(60)),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                edgeHubCredentials.Identity,
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20));
            var connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), identityProvider);

            try
            {
                Mock.Get(credentialsCache)
                .Setup(c => c.Get(edgeHubCredentials.Identity))
                .ReturnsAsync(Option.Some(edgeHubCredentials));
                Assert.NotNull(edgeHubCredentials);
                Assert.NotNull(edgeHubCredentials.Identity);

                // Set Edge hub desired properties
                await this.SetDesiredProperties(registryManager, edgeDeviceId);

                var endpointFactory = new EndpointFactory(connectionManager, new RoutingMessageConverter(), edgeDeviceId);
                var routeFactory    = new EdgeRouteFactory(endpointFactory);

                var            dbStoreProvider            = new InMemoryDbStoreProvider();
                IStoreProvider storeProvider              = new StoreProvider(dbStoreProvider);
                IEntityStore <string, TwinInfo> twinStore = storeProvider.GetEntityStore <string, TwinInfo>("twins");
                var      twinManager             = new TwinManager(connectionManager, twinCollectionMessageConverter, twinMessageConverter, Option.Some(twinStore));
                var      routerConfig            = new RouterConfig(Enumerable.Empty <Route>());
                TimeSpan defaultTimeout          = TimeSpan.FromSeconds(60);
                var      endpointExecutorFactory = new SyncEndpointExecutorFactory(new EndpointExecutorConfig(defaultTimeout, new FixedInterval(0, TimeSpan.FromSeconds(1)), defaultTimeout, true));
                Router   router = await Router.CreateAsync(Guid.NewGuid().ToString(), iothubHostName, routerConfig, endpointExecutorFactory);

                IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager);
                IEdgeHub             edgeHub             = new RoutingEdgeHub(router, new RoutingMessageConverter(), connectionManager, twinManager, edgeDeviceId, invokeMethodHandler, Mock.Of <IDeviceConnectivityManager>());
                cloudConnectionProvider.BindEdgeHub(edgeHub);

                var versionInfo = new VersionInfo("v1", "b1", "c1");

                // Create Edge Hub connection
                EdgeHubConnection edgeHubConnection = await EdgeHubConnection.Create(
                    edgeHubCredentials.Identity,
                    edgeHub,
                    twinManager,
                    connectionManager,
                    routeFactory,
                    twinCollectionMessageConverter,
                    twinMessageConverter,
                    versionInfo,
                    new NullDeviceScopeIdentitiesCache()
                    );

                await Task.Delay(TimeSpan.FromMinutes(1));

                // Get and Validate EdgeHubConfig
                Option <EdgeHubConfig> edgeHubConfigOption = await edgeHubConnection.GetConfig();

                Assert.True(edgeHubConfigOption.HasValue);
                EdgeHubConfig edgeHubConfig = edgeHubConfigOption.OrDefault();
                Assert.Equal("1.0", edgeHubConfig.SchemaVersion);
                Assert.NotNull(edgeHubConfig.Routes);
                Assert.NotNull(edgeHubConfig.StoreAndForwardConfiguration);
                Assert.Equal(20, edgeHubConfig.StoreAndForwardConfiguration.TimeToLiveSecs);

                List <(string Name, string Value, Route Route)> routes = edgeHubConfig.Routes.ToList();
                Assert.Equal(4, routes.Count);

                (string Name, string Value, Route Route)route1 = routes[0];
                Assert.NotNull(route1);
                Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                Assert.Equal("route1", route1.Name);
                Assert.Equal("from /* INTO $upstream", route1.Value);

                (string Name, string Value, Route Route)route2 = routes[1];
                Assert.NotNull(route2);
                Endpoint endpoint = route2.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                Assert.Equal("route2", route2.Name);
                Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                (string Name, string Value, Route Route)route3 = routes[2];
                Assert.NotNull(route3);
                endpoint = route3.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module3/input1", endpoint.Id);
                Assert.Equal("route3", route3.Name);
                Assert.Equal("from /modules/module2 INTO BrokeredEndpoint(\"/modules/module3/inputs/input1\")", route3.Value);

                (string Name, string Value, Route Route)route4 = routes[3];
                Assert.NotNull(route4);
                endpoint = route4.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module4/input1", endpoint.Id);
                Assert.Equal("route4", route4.Name);
                Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module4/inputs/input1\")", route4.Value);

                // Make sure reported properties were updated appropriately
                EdgeHubConnection.ReportedProperties reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(0, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Simulate a module and a downstream device that connects to Edge Hub.

                string             moduleId = "module1";
                string             sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{edgeDeviceId}/modules/{moduleId}");
                string             moduleConnectionstring  = $"HostName={iothubHostName};DeviceId={edgeDeviceId};ModuleId={moduleId};SharedAccessSignature={sasToken}";
                IClientCredentials moduleClientCredentials = identityFactory.GetWithConnectionString(moduleConnectionstring);
                var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                string downstreamDeviceId = "device1";
                sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{downstreamDeviceId}");
                string             downstreamDeviceConnectionstring = $"HostName={iothubHostName};DeviceId={downstreamDeviceId};SharedAccessSignature={sasToken}";
                IClientCredentials downstreamDeviceCredentials      = identityFactory.GetWithConnectionString(downstreamDeviceConnectionstring);
                var downstreamDeviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                // Connect the module and downstream device and make sure the reported properties are updated as expected.
                await connectionManager.AddDeviceConnection(moduleClientCredentials.Identity, moduleProxy);

                await connectionManager.AddDeviceConnection(downstreamDeviceCredentials.Identity, downstreamDeviceProxy);

                string moduleIdKey = $"{edgeDeviceId}/{moduleId}";
                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[downstreamDeviceId].Status);
                Assert.NotNull(reportedProperties.Clients[downstreamDeviceId].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[downstreamDeviceId].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Update desired propertied and make sure callback is called with valid values
                bool callbackCalled = false;

                Task ConfigUpdatedCallback(EdgeHubConfig updatedConfig)
                {
                    Assert.NotNull(updatedConfig);
                    Assert.NotNull(updatedConfig.StoreAndForwardConfiguration);
                    Assert.NotNull(updatedConfig.Routes);

                    routes = updatedConfig.Routes.ToList();
                    Assert.Equal(4, routes.Count);

                    route1 = routes[0];
                    Assert.NotNull(route1);
                    Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                    Assert.Equal("route1", route1.Name);
                    Assert.Equal("from /* INTO $upstream", route1.Value);

                    route2 = routes[1];
                    Assert.NotNull(route2);
                    endpoint = route2.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                    Assert.Equal("route2", route2.Name);
                    Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                    route3 = routes[2];
                    Assert.NotNull(route3);
                    endpoint = route3.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module5/input1", endpoint.Id);
                    Assert.Equal("route4", route3.Name);
                    Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", route3.Value);

                    route4 = routes[3];
                    Assert.NotNull(route4);
                    endpoint = route4.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module6/input1", endpoint.Id);
                    Assert.Equal("route5", route4.Name);
                    Assert.Equal("from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", route4.Value);

                    callbackCalled = true;
                    return(Task.CompletedTask);
                }

                edgeHubConnection.SetConfigUpdatedCallback(ConfigUpdatedCallback);
                await this.UpdateDesiredProperties(registryManager, edgeDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(5));

                Assert.True(callbackCalled);

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Disconnect the downstream device and make sure the reported properties are updated as expected.
                await connectionManager.RemoveDeviceConnection(moduleIdKey);

                await connectionManager.RemoveDeviceConnection(downstreamDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(1, reportedProperties.Clients.Count);
                Assert.True(reportedProperties.Clients.ContainsKey(moduleIdKey));
                Assert.False(reportedProperties.Clients.ContainsKey(downstreamDeviceId));
                Assert.Equal(ConnectionStatus.Disconnected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // If the edge hub restarts, clear out the connected devices in the reported properties.
                await EdgeHubConnection.Create(
                    edgeHubCredentials.Identity,
                    edgeHub,
                    twinManager,
                    connectionManager,
                    routeFactory,
                    twinCollectionMessageConverter,
                    twinMessageConverter,
                    versionInfo,
                    new NullDeviceScopeIdentitiesCache());

                await Task.Delay(TimeSpan.FromMinutes(1));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Null(reportedProperties.Clients);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);
            }
            finally
            {
                try
                {
                    await RegistryManagerHelper.RemoveDevice(edgeDeviceId, registryManager);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Esempio n. 60
0
 private void Launcher_OnGameLaunch(object sender, string status, VersionInfo versionInfo)
 {
     _frmPrs.ChangeStatus(LangManager.GetLangFromResource(status));
 }