private static CacheConfiguration GenerateCacheConfiguration(ConfigurationInfo info)
        {
            CacheConfiguration configuration = new CacheConfiguration();

            foreach (ConfigNode node in info)
            {                                
                configuration.SchedulerConfiguration.Add(node.Convert());
            }

            return configuration;
        }
		ConfigurationInfo GetConfigurationInfo()
		{
			if (_configurationInfo == null && !_configurations.TryGetValue(Configuration ?? "", out _configurationInfo))
			{
				var client = GetClient();

				try
				{
					var info = client.GetInfo(Configuration);

					MappingSchema ms;

					if (string.IsNullOrEmpty(info.MappingSchemaType))
					{
						ms = new MappingSchema(
							info.ConfigurationList
								.Select(c => ContextIDPrefix + "." + c).Concat(new[] { ContextIDPrefix }).Concat(info.ConfigurationList)
								.Select(c => new MappingSchema(c)).     Concat(new[] { MappingSchema.Default })
								.ToArray());
					}
					else
					{
						var type = Type.GetType(info.MappingSchemaType);
						ms = (MappingSchema)Activator.CreateInstance(type);
					}

					_configurationInfo = new ConfigurationInfo
					{
						LinqServiceInfo = info,
						MappingSchema   = ms,
					};
				}
				finally
				{
					((IDisposable)client).Dispose();
				}
			}

			return _configurationInfo;
		}
 public EdgeHubDockerRuntimeModule(
     ModuleStatus desiredStatus,
     RestartPolicy restartPolicy,
     DockerConfig config,
     int exitCode,
     string statusDescription,
     DateTime lastStartTime,
     DateTime lastExitTime,
     int restartCount,
     DateTime lastRestartTime,
     ModuleStatus runtimeStatus,
     ConfigurationInfo configuration,
     IDictionary <string, EnvVal> env,
     string version = "")
     : base(
         Core.Constants.EdgeHubModuleName,
         version,
         desiredStatus,
         restartPolicy,
         config,
         exitCode,
         statusDescription,
         lastStartTime,
         lastExitTime,
         restartCount,
         lastRestartTime,
         runtimeStatus,
         configuration,
         env)
 {
     // You maybe wondering why we are setting this here again even though
     // the base class does this assignment. This is due to a behavior
     // in C# where if you have an assignment to a read-only virtual property
     // from a base constructor when it has been overriden in a sub-class, the
     // assignment becomes a no-op.  In order to fix this we need to assign
     // this here again so that the correct property assignment happens for real!
     this.RestartPolicy = Preconditions.CheckIsDefined(restartPolicy);
     this.Version       = version ?? string.Empty;
 }
        public ActionResult GetApplicationVersionInfo()
        {
            var assembly = this.GetType().GetTypeInfo().Assembly;

            ConfigurationInfo avi = new ConfigurationInfo()
            {
                BaseUri          = configuration["BASE_URI"],
                BasePath         = configuration["BASE_PATH"],
                Environment      = configuration["APP_ENVIRONMENT_TITLE"],
                SourceCommit     = configuration["OPENSHIFT_BUILD_COMMIT"],
                SourceRepository = configuration["OPENSHIFT_BUILD_SOURCE"],
                SourceReference  = configuration["OPENSHIFT_BUILD_REFERENCE"],
                FileCreationTime = System.IO.File.GetLastWriteTimeUtc(assembly.Location).ToString("O"), // Use the round trip format as it includes the time zone.
                FileVersion      = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion,
                ClientTimeoutWarningInMinutes         = configuration.UserTimeoutWarningInMinutes(),
                ClientTimeoutWarningDurationInMinutes = configuration.UserTimeoutWarningDurationInMinutes(),
                DefaultTimeoutWarningInMinutes        = configuration.DefaultTimeoutWarningInMinutes(),
                DefaultWarningDurationInMinutes       = configuration.DefaultTimeoutWarningDurationInMinutes(),
            };

            return(Json(avi));
        }
Exemple #5
0
        public ActionResult GetApplicationVersionInfo()
        {
            var assembly = this.GetType().GetTypeInfo().Assembly;

            ConfigurationInfo avi = new ConfigurationInfo()
            {
                BaseUri          = configuration.GetBaseUri(),
                BasePath         = configuration.GetBasePath(),
                Environment      = configuration.GetEnvironmentTitle(),
                SourceCommit     = configuration.GetBuildCommitId(),
                SourceRepository = configuration.GetBuildSource(),
                SourceReference  = configuration.GetBuildVersion(),
                FileCreationTime = System.IO.File.GetLastWriteTimeUtc(assembly.Location).ToString("O"), // Use the round trip format as it includes the time zone.
                FileVersion      = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion,
                ClientTimeoutWarningInMinutes         = configuration.UserTimeoutWarningInMinutes(),
                ClientTimeoutWarningDurationInMinutes = configuration.UserTimeoutWarningDurationInMinutes(),
                DefaultTimeoutWarningInMinutes        = configuration.DefaultTimeoutWarningInMinutes(),
                DefaultWarningDurationInMinutes       = configuration.DefaultTimeoutWarningDurationInMinutes(),
            };

            return(Json(avi));
        }
Exemple #6
0
 // Key released
 private void listconfigs_KeyUp(object sender, KeyEventArgs e)
 {
     // Nothing selected?
     if (listconfigs.SelectedItems.Count == 0)
     {
         // Disable panels
         gameconfig = null;
         configinfo = null;
         configdata.FixedResourceLocationList(new DataLocationList());
         configdata.EditResourceLocationList(new DataLocationList());
         nodebuildersave.SelectedIndex = -1;
         nodebuildertest.SelectedIndex = -1;
         testapplication.Text          = "";
         testparameters.Text           = "";
         shortpaths.Checked            = false;
         skill.Value = 0;
         skill.ClearInfo();
         customparameters.Checked = false;
         tabs.Enabled             = false;
         listtextures.Items.Clear();
     }
 }
 DockerRuntimeModule(
     string name,
     string version,
     string type,
     ModuleStatus status,
     RestartPolicy restartPolicy,
     DockerConfig config,
     int?exitCode,
     string statusDescription,
     DateTime lastStartTimeUtc,
     DateTime lastExitTimeUtc,
     int restartCount,
     DateTime lastRestartTimeUtc,
     ModuleStatus runtimeStatus,
     ImagePullPolicy imagePullPolicy,
     uint startupOrder,
     ConfigurationInfo configurationInfo,
     IDictionary <string, EnvVal> env)
     : this(
         name,
         version,
         status,
         restartPolicy,
         config,
         exitCode ?? 0,
         statusDescription,
         lastStartTimeUtc,
         lastExitTimeUtc,
         restartCount,
         lastRestartTimeUtc,
         runtimeStatus,
         imagePullPolicy,
         startupOrder,
         configurationInfo,
         env)
 {
     Preconditions.CheckArgument(type?.Equals("docker") ?? false);
 }
Exemple #8
0
 public EdgeAgentDockerRuntimeModule(
     DockerConfig config,
     ModuleStatus runtimeStatus,
     int exitCode,
     string statusDescription,
     DateTime lastStartTimeUtc,
     DateTime lastExitTime,
     ConfigurationInfo configuration,
     IDictionary <string, EnvVal> env,
     string version = "")
     : base(
         Core.Constants.EdgeAgentModuleName,
         version,
         ModuleStatus.Running,
         RestartPolicy.Always,
         config,
         exitCode,
         statusDescription,
         lastStartTimeUtc,
         lastExitTime,
         0,
         DateTime.MinValue,
         runtimeStatus,
         configuration,
         env)
 {
     // You maybe wondering why we are setting this here again even though
     // the base class does this assignment. This is due to a behavior
     // in C# where if you have an assignment to a read-only virtual property
     // from a base constructor when it has been overriden in a sub-class, the
     // assignment becomes a no-op.  In order to fix this we need to assign
     // this here again so that the correct property assignment happens for real!
     this.RestartPolicy      = RestartPolicy.Always;
     this.DesiredStatus      = ModuleStatus.Running;
     this.RestartCount       = 0;
     this.LastRestartTimeUtc = DateTime.MinValue;
     this.Version            = version ?? string.Empty;
 }
 public KubernetesModule(
     string name,
     string version,
     string type,
     ModuleStatus status,
     RestartPolicy restartPolicy,
     ConfigurationInfo configurationInfo,
     IDictionary <string, EnvVal> env,
     KubernetesConfig settings,
     ImagePullPolicy imagePullPolicy,
     KubernetesModuleOwner owner)
 {
     this.Name              = name;
     this.Version           = version;
     this.Type              = type;
     this.DesiredStatus     = status;
     this.RestartPolicy     = restartPolicy;
     this.ConfigurationInfo = configurationInfo ?? new ConfigurationInfo(string.Empty);
     this.Env             = env?.ToImmutableDictionary() ?? ImmutableDictionary <string, EnvVal> .Empty;
     this.Config          = settings;
     this.ImagePullPolicy = imagePullPolicy;
     this.Owner           = owner;
 }
        private static ConfigurationInfo ParseXMLIntoConfigurationInfo(XmlDocument doc)
        {            
            XmlNode mediums = doc.SelectSingleNode("SharpCache/CacheMediums");
            if (mediums == null)
            {
                throw new NullReferenceException("SharpCache/CacheMediums element is missing.");
            }

            ConfigurationInfo collection = new ConfigurationInfo();

            foreach (XmlNode node in mediums.ChildNodes)
            {
                ConfigNode configNode = ParseConfigNode(node);
                if (configNode.Validate() == false)
                {
                    throw new Exception("Medium node is invalid.");
                }

                collection.Add(configNode);
            }

            return collection;
        }
Exemple #11
0
        private void pasteresources_Click(object sender, EventArgs e)
        {
            if (listconfigs.SelectedIndices.Count < 1)
            {
                return;
            }

            // Get current configinfo
            ConfigurationInfo current = listconfigs.SelectedItems[0].Tag as ConfigurationInfo;

            current.PasteResourcesFrom(configinfocopy);

            // Update display
            listconfigs_SelectedIndexChanged(listconfigs, EventArgs.Empty);

            // Resources need reloading?
            if (General.Map != null && General.Map.ConfigSettings.Name == current.Name)
            {
                reloadresources = true;
            }

            General.Interface.DisplayStatus(StatusType.Info, "Pasted resources from \"" + configinfocopy.Name + "\"");
        }
Exemple #12
0
 public DockerModule(
     string name,
     string version,
     ModuleStatus desiredStatus,
     RestartPolicy restartPolicy,
     DockerConfig config,
     ImagePullPolicy imagePullPolicy,
     uint priority,
     ConfigurationInfo configurationInfo,
     IDictionary <string, EnvVal> env,
     IDictionary <string, string> secrets)
 {
     this.Name              = name;
     this.Version           = version ?? string.Empty;
     this.DesiredStatus     = Preconditions.CheckIsDefined(desiredStatus);
     this.Config            = Preconditions.CheckNotNull(config, nameof(config));
     this.RestartPolicy     = Preconditions.CheckIsDefined(restartPolicy);
     this.ImagePullPolicy   = Preconditions.CheckIsDefined(imagePullPolicy);
     this.Priority          = priority;
     this.ConfigurationInfo = configurationInfo ?? new ConfigurationInfo(string.Empty);
     this.Env     = env?.ToImmutableDictionary() ?? ImmutableDictionary <string, EnvVal> .Empty;
     this.Secrets = secrets?.ToImmutableDictionary() ?? ImmutableDictionary <string, string> .Empty;
 }
Exemple #13
0
 public TestModuleBase(
     string name,
     string version,
     string type,
     ModuleStatus desiredStatus,
     TConfig config,
     RestartPolicy restartPolicy,
     ImagePullPolicy imagePullPolicy,
     uint startupOrder,
     ConfigurationInfo configuration,
     IDictionary <string, EnvVal> env)
 {
     this.Name              = name;
     this.Version           = Preconditions.CheckNotNull(version, nameof(version));
     this.Type              = Preconditions.CheckNotNull(type, nameof(type));
     this.DesiredStatus     = Preconditions.CheckNotNull(desiredStatus, nameof(desiredStatus));
     this.Config            = Preconditions.CheckNotNull(config, nameof(config));
     this.RestartPolicy     = Preconditions.CheckIsDefined(restartPolicy);
     this.ImagePullPolicy   = Preconditions.CheckIsDefined(imagePullPolicy);
     this.StartupOrder      = startupOrder;
     this.ConfigurationInfo = configuration ?? new ConfigurationInfo();
     this.Env = env?.ToImmutableDictionary() ?? ImmutableDictionary <string, EnvVal> .Empty;
 }
        // OK clicked
        private void apply_Click(object sender, EventArgs e)
        {
            // Apply configuration items
            foreach (ListViewItem lvi in listconfigs.Items)
            {
                // Get configuration item
                ConfigurationInfo ci = lvi.Tag as ConfigurationInfo;

                // Find same configuration info in originals
                foreach (ConfigurationInfo oci in General.Configs)
                {
                    // Apply settings when they match
                    if (string.Compare(ci.Filename, oci.Filename) == 0)
                    {
                        oci.Apply(ci);
                    }
                }
            }

            // Close
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Exemple #15
0
        /// <summary>
        /// 根据传入Model,并返回Model
        /// </summary>
        public bool Add(ConfigurationInfo configurationInfo)
        {
            string sql = "INSERT INTO tblConfigurationInfo (ConfigurationKey, ConfigurationValue, Description, ConfigurationNo, HashCode)  VALUES (@ConfigurationKey, @ConfigurationValue, @Description, @ConfigurationNo, @HashCode)";

            MySqlParameter[] para = new MySqlParameter[]
            {
                new MySqlParameter("@ConfigurationKey", ToDBValue(configurationInfo.ConfigurationKey)),
                new MySqlParameter("@ConfigurationValue", ToDBValue(configurationInfo.ConfigurationValue)),
                new MySqlParameter("@Description", ToDBValue(configurationInfo.Description)),
                new MySqlParameter("@ConfigurationNo", ToDBValue(configurationInfo.ConfigurationNo)),
                new MySqlParameter("@HashCode", ToDBValue(configurationInfo.HashCode)),
            };

            int AddId = (int)MyDBHelper.ExecuteScalar(sql, para);

            if (AddId == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #16
0
        static IEnumerable <object[]> CreateTestData()
        {
            var defaultConfigurationInfo               = new ConfigurationInfo();
            IDictionary <string, EnvVal> envVars       = new Dictionary <string, EnvVal>();
            Option <TestPlanRecorder>    recordKeeper1 = Option.Some(new TestPlanRecorder());
            Option <TestPlanRecorder>    recordKeeper2 = Option.Some(new TestPlanRecorder());
            Option <TestPlanRecorder>    recordKeeper3 = Option.Some(new TestPlanRecorder());
            var tt = new List <TestCommandType>
            {
                TestCommandType.TestCreate,
                TestCommandType.TestCreate,
                TestCommandType.TestCreate,
                TestCommandType.TestCreate,
                TestCommandType.TestCreate
            };
            var tm = new List <TestModule> {
                new TestModule("module1", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image1"), RestartPolicy.OnUnhealthy, defaultConfigurationInfo, envVars),
                new TestModule("module2", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image2"), RestartPolicy.OnUnhealthy, defaultConfigurationInfo, envVars),
                new TestModule("module3", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image3"), RestartPolicy.OnUnhealthy, defaultConfigurationInfo, envVars),
                new TestModule("module4", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image4"), RestartPolicy.OnUnhealthy, defaultConfigurationInfo, envVars),
                new TestModule("module5", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image5"), RestartPolicy.OnUnhealthy, defaultConfigurationInfo, envVars)
            };

            (Option <TestPlanRecorder> recorder, List <TestRecordType> moduleExecutionList, List <ICommand> commandList)[] testInputRecords =
Exemple #17
0
        private void pasteall_Click(object sender, EventArgs e)
        {
            if (listconfigs.SelectedIndices.Count < 1)
            {
                return;
            }

            // Get current configinfo
            ConfigurationInfo current = listconfigs.SelectedItems[0].Tag as ConfigurationInfo;

            current.PasteFrom(configinfocopy);

            // Update display
            cbEngineSelector.Text = string.Empty;             // Otherwise current text from cbEngineSelector will override the pasted one
            listconfigs_SelectedIndexChanged(listconfigs, EventArgs.Empty);

            // Resources need reloading?
            if (General.Map != null && General.Map.ConfigSettings.Name == current.Name)
            {
                reloadresources = true;
            }

            General.Interface.DisplayStatus(StatusType.Info, "Pasted game configuration from \"" + configinfocopy.Name + "\"");
        }
Exemple #18
0
 /// <summary>
 /// Creates a new AppSecurityContext.
 /// </summary>
 public AppSecurityContext(ConfigurationInfo lcf)
 {
     Lcf = lcf;
 }
Exemple #19
0
 /// <summary>
 /// This is a copy constructor, used primarily for get-command.
 /// </summary>
 internal ConfigurationInfo(ConfigurationInfo other)
     : base(other)
 {
 }
        // Map name selected
        private void mapslist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
            {
                return;                           //mxd. Don't want to trigger this twice
            }
            DataLocationList locations;
            DataLocationList listedlocations;
            string           scriptconfig = string.Empty;   //mxd

            // Map previously selected?
            if (!string.IsNullOrEmpty(selectedmapname))
            {
                // Get locations from previous selected map settings
                locations       = new DataLocationList(mapsettings, "maps." + selectedmapname + ".resources");
                listedlocations = datalocations.GetResources();

                // Remove data locations that this map has in its config
                foreach (DataLocation dl in locations)
                {
                    listedlocations.Remove(dl);
                }

                // Set new data locations
                datalocations.EditResourceLocationList(listedlocations);

                // Done
                selectedmapname = null;
            }

            // Anything selected?
            if (mapslist.SelectedItems.Count > 0)
            {
                // Get the map name
                selectedmapname = mapslist.SelectedItems[0].Text;
                options         = new MapOptions(mapsettings, selectedmapname, longtexturenames.Enabled);

                // Get locations from previous selected map settings
                locations       = new DataLocationList(mapsettings, "maps." + selectedmapname + ".resources");
                listedlocations = datalocations.GetResources();

                // Add data locations that this map has in its config
                foreach (DataLocation dl in locations)
                {
                    if (!listedlocations.Contains(dl))
                    {
                        listedlocations.Add(dl);
                    }
                }

                // Set new data locations
                datalocations.EditResourceLocationList(listedlocations);

                //mxd. Select script compiler
                ConfigurationInfo info = config.SelectedItem as ConfigurationInfo;
                if (info != null)
                {
                    if (!string.IsNullOrEmpty(options.ScriptCompiler) && General.CompiledScriptConfigs.ContainsKey(options.ScriptCompiler))
                    {
                        scriptconfig = options.ScriptCompiler;
                    }
                    else if (!string.IsNullOrEmpty(info.DefaultScriptCompiler) && General.CompiledScriptConfigs.ContainsKey(info.DefaultScriptCompiler))
                    {
                        scriptconfig = info.DefaultScriptCompiler;
                    }
                }
            }

            //mxd. Select proper script compiler
            if (!string.IsNullOrEmpty(scriptconfig))
            {
                scriptcompiler.Enabled      = true;
                scriptcompiler.SelectedItem = General.CompiledScriptConfigs[scriptconfig];
                scriptcompilerlabel.Enabled = true;
            }
            else
            {
                scriptcompiler.Enabled       = false;
                scriptcompiler.SelectedIndex = -1;
                scriptcompilerlabel.Enabled  = false;
            }
        }
        // OK clicked
        private void apply_Click(object sender, EventArgs e)
        {
            // Configuration selected?
            if (config.SelectedIndex == -1)
            {
                // Select a configuration!
                MessageBox.Show(this, "Please select a game configuration to use for editing your map.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                config.Focus();
                return;
            }

            //mxd. Script configuration selected?
            if (scriptcompiler.Enabled && scriptcompiler.SelectedIndex == -1)
            {
                // Select a configuration!
                MessageBox.Show(this, "Please select a script type to use for editing your map.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                scriptcompiler.Focus();
                return;
            }

            // Collect information
            ConfigurationInfo configinfo = (config.SelectedItem as ConfigurationInfo);             //mxd
            DataLocationList  locations  = datalocations.GetResources();

            // Resources are valid? (mxd)
            if (!datalocations.ResourcesAreValid())
            {
                MessageBox.Show(this, "Cannot open map: at least one resource doesn't exist!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                datalocations.Focus();
                return;
            }

            // No map selected?
            if (mapslist.SelectedItems.Count == 0)
            {
                // Choose a map!
                MessageBox.Show(this, "Please select a map to load for editing.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mapslist.Focus();
                return;
            }

            //mxd. We cant't deal with this... We just can't...
            if (!configinfo.ValidateMapName(mapslist.SelectedItems[0].Text.ToUpperInvariant()))
            {
                // Choose a different map!
                MessageBox.Show(this, "Selected map name conflicts with a lump name defined for current map format.\nPlease rename the map and try again.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mapslist.Focus();
                return;
            }

            // Check if we should warn the user for missing resources
            if ((!wadfile.IsIWAD) && (locations.Count == 0) && (configinfo.Resources.Count == 0))
            {
                if (MessageBox.Show(this, "You are about to load a map without selecting any resources. Textures, flats and " +
                                    "sprites may not be shown correctly or may not show up at all. Do you want to continue?", Application.ProductName,
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            // Apply changes
            options.ClearResources();
            options.ConfigFile    = configinfo.Filename;
            options.CurrentName   = mapslist.SelectedItems[0].Text;
            options.StrictPatches = strictpatches.Checked;
            options.CopyResources(locations);

            //mxd. Store script compiler
            if (scriptcompiler.Enabled)
            {
                ScriptConfiguration scriptcfg = scriptcompiler.SelectedItem as ScriptConfiguration;
                foreach (KeyValuePair <string, ScriptConfiguration> group in General.CompiledScriptConfigs)
                {
                    if (group.Value == scriptcfg)
                    {
                        options.ScriptCompiler = group.Key;
                        break;
                    }
                }
            }

            //mxd. Use long texture names?
            if (longtexturenames.Enabled)
            {
                options.UseLongTextureNames = longtexturenames.Checked;
            }

            //mxd. Resource usage
            options.UseResourcesInReadonlyMode = readonlyresources.Checked;

            // Hide window
            wadfile.Dispose();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        private IConfiguration ProcessConfiguration(ConfigurationInfo configData, string userName)
        {
            if (configData == null)
            {
                return null; 
            }

            var configUpgraded = false;

            if (configData.Version < CurrentVersion)
            {
                configData.Content = UpgradeSerializedData(configData.Content, configData.Version, CurrentVersion);
                configUpgraded = true;
            }

            var configuration = BaseConfiguration.DeserializeFromXml(configData.Content);

            configuration.GroupId = configData.GroupId;
            configuration.GroupName = configData.GroupName;

            if (!configUpgraded)
            {
                return configuration;
            }

            configuration.VersionId = CurrentVersion;
            SaveConfiguration(configuration, userName);

            return configuration;
        }
        public static void AddConfiguration([JetBrains.Annotations.NotNull] string configuration, [JetBrains.Annotations.NotNull] string connectionString, IDataProvider dataProvider = null)
        {
            if (configuration    == null) throw new ArgumentNullException("configuration");
            if (connectionString == null) throw new ArgumentNullException("connectionString");

            _configurations[configuration] = new ConfigurationInfo(
                connectionString,
                dataProvider ?? FindProvider(configuration, _dataProviders, _dataProviders[DefaultDataProvider]));
        }
Exemple #24
0
        /// <summary>
        /// Gets a list of matching commands.
        /// </summary>
        /// <param name="pattern">Command pattern.</param>
        /// <param name="context">Execution context.</param>
        /// <param name="commandOrigin">Command origin.</param>
        /// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
        /// <param name="moduleVersionRequired">Specific module version to be required.</param>
        /// <param name="useFuzzyMatching">Use fuzzy matching.</param>
        /// <param name="useAbbreviationExpansion">Use abbreviation expansion for matching.</param>
        /// <returns>Returns matching CommandInfo IEnumerable.</returns>
        internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))))
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName                  = Path.GetFileNameWithoutExtension(modulePath);
                    List <PSModuleInfo> modules        = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo        tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name) ||
                                    (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) ||
                                    (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase)))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                    case CommandTypes.Alias:
                                        current = new AliasInfo(entry.Value.Name, definition: null, context);
                                        break;

                                    case CommandTypes.Function:
                                        current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Filter:
                                        current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Configuration:
                                        current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Cmdlet:
                                        current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context);
                                        break;

                                    default:
                                        Dbg.Assert(false, "cannot be hit");
                                        break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return(current);
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = Path.GetFileNameWithoutExtension(modulePath);

                    IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context);

                    if (exportedCommands == null)
                    {
                        continue;
                    }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
                    }

                    // moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands)
                    {
                        string       commandName  = pair.Key;
                        CommandTypes commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName) ||
                            (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) ||
                            (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase)))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return(new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #25
0
        static void Main(string[] args)
        {
            /************************************************************
            * Please change these accordingly to your own environment  *
            ************************************************************/
            String username = "";
            String password = "";
            String domain   = "";

            AuthenticationType authType    = AuthenticationType.WindowsDefault;
            String             hostAddress = "localhost";
            int port = 80;

            if (authType == AuthenticationType.Basic)
            {
                port = 443; //SSL
            }

            /************************************************************
            * Beginning of program                                     *
            ************************************************************/
            Console.WriteLine("Milestone SDK Bookmarks demo (XProtect Corporate only)");
            Console.WriteLine("Creates 2 new bookmarks and retrieves them using ");
            Console.WriteLine("  1) BookmarkSearchTime ");
            Console.WriteLine("  2) BookmarkSearchFromBookmark");
            Console.WriteLine("  3) BookmarkGet");
            Console.WriteLine("  4) BookmarkDelete");
            Console.WriteLine("");


            #region Connect to the Management Server, get configuration, and extract the cameras

            RecorderInfo[]             recorderInfo = new RecorderInfo[0];
            LoginInfo                  loginInfo    = null;
            ServerCommandServiceClient scs          = null;
            switch (authType)
            {
            case AuthenticationType.Basic:
                _basicConnection = new BasicConnection(username, password, hostAddress, port);
                loginInfo        = _basicConnection.Login(IntegrationId, Version, IntegrationName);
                _basicConnection.GetConfiguration(loginInfo.Token);

                ConfigurationInfo confInfoBasic =
                    _basicConnection.ConfigurationInfo;
                recorderInfo = confInfoBasic.Recorders;

                scs = _basicConnection.Server;

                break;

            case AuthenticationType.Windows:
            case AuthenticationType.WindowsDefault:
                _ntlmConnection = new NtlmConnection(domain, authType, username, password, hostAddress,
                                                     port);
                loginInfo = _ntlmConnection.Login(IntegrationId, Version, IntegrationName);
                _ntlmConnection.GetConfiguration(loginInfo.Token);

                ConfigurationInfo confInfoNtlm = _ntlmConnection.ConfigurationInfo;
                recorderInfo = confInfoNtlm.Recorders;

                scs = _ntlmConnection.Server;
                break;

            default:
                //Empty
                break;
            }

            #endregion

            #region Find recording servers attached to the management server

            //Get recording servers
            int recorders = recorderInfo.Length;
            Console.WriteLine("{0} Corporate Recording Server found", recorders);
            if (recorders == 0)
            {
                Console.WriteLine("");
                Console.WriteLine("Press any key");
                Console.ReadKey();
                return;
            }

            #endregion


            DateTime timeNow = DateTime.Now;

            // get cameras for the first recorder
            RecorderInfo recorder = recorderInfo[0];
            Console.WriteLine("");
            Console.WriteLine("Processing recording server {0}", recorder.Name);
            Console.WriteLine("");

            #region Find all cameras defined on the recording server

            // extract info about the recording server
            List <CameraInfo> cameras = recorder.Cameras.ToList();

            #endregion



            // now-5:10min:                                       BookmarkSearchTime start
            // now-5:00min: (beginTime)                                         |                                                  BookmarkGet
            // now-4:59min: start recording 1                                   |
            // now-4:55min: start bookmark 1                                    |
            // now-4:45min: end bookmark 1                                      |
            //                                                                  |                BookmarkSearchFromBookmark
            // now-2:00min:                                                     |                            |
            // now-1:59min: start recording 2                                   |                            |
            // now-1:55min: start bookmark 2 (trigger time)                     |                            |
            // now-1:45min: end bookmark 2                                      |                            |
            // now                                                              v                            V

            #region create first bookmark

            Guid cameraGuid = cameras.First().DeviceId;

            Console.WriteLine("Creating the first bookmark");
            MediaDeviceType[] mediaDeviceTypes = new MediaDeviceType[3];
            mediaDeviceTypes[0] = MediaDeviceType.Camera;
            mediaDeviceTypes[1] = MediaDeviceType.Microphone;
            mediaDeviceTypes[2] = MediaDeviceType.Speaker;



            DateTime     timeBegin = timeNow.AddMinutes(-5);
            TimeDuration td        = new TimeDuration()
            {
                MicroSeconds = (int)TimeSpan.FromMinutes(30).TotalMilliseconds * 1000
            };

            StringBuilder bookmarkRef    = new StringBuilder();
            StringBuilder bookmarkHeader = new StringBuilder();
            StringBuilder bookmarkDesc   = new StringBuilder();
            bookmarkRef.AppendFormat("MyBookmark-{0}", timeBegin.ToLongTimeString());
            bookmarkHeader.AppendFormat("AutoBookmark-{0}", timeBegin.ToLongTimeString());
            bookmarkDesc.AppendFormat("AutoBookmark-{0} set for a duration of {1} seconds",
                                      timeBegin.ToLongTimeString(), (timeBegin.AddSeconds(10) - timeBegin.AddSeconds(1)).Seconds);

            Bookmark newBookmark = null;
            try
            {
                newBookmark = scs.BookmarkCreate(loginInfo.Token, cameraGuid,
                                                 timeBegin.AddSeconds(1),
                                                 timeBegin.AddSeconds(5),
                                                 timeBegin.AddSeconds(10),
                                                 bookmarkRef.ToString(),
                                                 bookmarkHeader.ToString(),
                                                 bookmarkDesc.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("BookmarkCreate: " + ex.Message);
                Console.WriteLine("Press any Key to exit...");
                Console.ReadKey();
                Environment.Exit(0);
            }

            if (newBookmark == null)
            {
                Console.WriteLine("New bookmark wasn't created.");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
                Environment.Exit(0);
            }

            Console.WriteLine("-> trigger time = {0}", newBookmark.TimeTrigged);
            Console.WriteLine("");


            #endregion

            Console.WriteLine("");
            Console.WriteLine("Waiting 20 sec ....");
            Console.WriteLine("");
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(20));

            #region Create a second bookmark

            Console.WriteLine("Creating a second bookmark - 2 minutes after the first bookmark");
            DateTime timeBegin2 = timeBegin.AddMinutes(2);
            bookmarkHeader.Length = 0;
            bookmarkDesc.Length   = 0;
            StringBuilder bookmarkRef2 = new StringBuilder();
            bookmarkRef2.AppendFormat("MyBookmark-{0}", timeBegin2.ToLongTimeString());
            bookmarkHeader.AppendFormat("AutoBookmark-{0}", timeBegin2.ToLongTimeString());
            bookmarkDesc.AppendFormat("AutoBookmark-{0} set for a duration of {1} seconds",
                                      timeBegin2.ToLongTimeString(), (timeBegin2.AddSeconds(10) - timeBegin2.AddSeconds(1)).Seconds);
            Bookmark newBookmark2 = scs.BookmarkCreate(loginInfo.Token, cameraGuid, timeBegin2.AddSeconds(1),
                                                       timeBegin2.AddSeconds(5), timeBegin2.AddSeconds(10)
                                                       , bookmarkRef2.ToString(), bookmarkHeader.ToString(), bookmarkDesc.ToString());

            Console.WriteLine("-> trigger time = {0}", newBookmark2.TimeTrigged);
            Console.WriteLine("");

            #endregion

            #region BookmarkSearchTime

            // Get max 10 of the bookmarks created after the specified time
            Console.WriteLine("");
            Console.WriteLine("Looking for bookmarks using BookmarkSearchTime (finding the 2 newly created)");
            Bookmark[] bookmarkList = scs.BookmarkSearchTime(loginInfo.Token, newBookmark.TimeBegin.AddSeconds(-10), td,
                                                             10, mediaDeviceTypes, new Guid[0], new string[0], "");
            if (bookmarkList.Length > 0)
            {
                Console.WriteLine("-> Found {0} bookmark(s)", bookmarkList.Length);
                int counter = 1;
                foreach (Bookmark bookmark in bookmarkList)
                {
                    Console.WriteLine("{0}:", counter);
                    Console.WriteLine("     Id  ={0} ", bookmark.Id);
                    Console.WriteLine("     Name={0} ", bookmark.Header);
                    Console.WriteLine("     Desc={0} ", bookmark.Description);
                    Console.WriteLine("     user={0} ", bookmark.User);
                    Console.WriteLine("     Device={0} Start={1} Stop={2}  ", bookmark.DeviceId, bookmark.TimeBegin,
                                      bookmark.TimeEnd);
                    counter++;
                }
            }
            else
            {
                Console.WriteLine("sorry no bookmarks found");
            }

            Console.WriteLine("");

            #endregion

            #region BookmarkSearchFromBookmark

            // Get the next (max 10) bookmarks after the first
            Console.WriteLine(
                "Looking for bookmarks using BookmarkSearchFromBookmark (finding the last of the 2 newly created)");
            Bookmark[] bookmarkListsFromBookmark = scs.BookmarkSearchFromBookmark(loginInfo.Token, newBookmark.Id, td,
                                                                                  10, mediaDeviceTypes, new Guid[0], new string[0], "");
            if (bookmarkListsFromBookmark.Length > 0)
            {
                Console.WriteLine("-> Found {0} bookmark(s)", bookmarkListsFromBookmark.Length);
                int counter = 1;
                foreach (Bookmark bookmark in bookmarkListsFromBookmark)
                {
                    Console.WriteLine("{0}:", counter);
                    Console.WriteLine("     Id  ={0} ", bookmark.Id);
                    Console.WriteLine("     Name={0} ", bookmark.Header);
                    Console.WriteLine("     Desc={0} ", bookmark.Description);
                    Console.WriteLine("     user={0} ", bookmark.User);
                    Console.WriteLine("     Device={0} Start={1} Stop={2}  ", bookmark.DeviceId, bookmark.TimeBegin,
                                      bookmark.TimeEnd);
                    counter++;
                }
            }
            else
            {
                Console.WriteLine("sorry no bookmarks found");
            }

            Console.WriteLine("");

            #endregion

            #region BookmarkGet

            // Get first created bookmark
            Console.WriteLine(
                "Looking for the first bookmarks using BookmarkGet  (finding the first of the 2 newly created)");
            Bookmark newBookmarkFetched = scs.BookmarkGet(loginInfo.Token, newBookmark.Id);
            if (newBookmarkFetched != null)
            {
                Console.WriteLine("-> A bookmarks is found");
                Console.WriteLine("     Id  ={0} ", newBookmarkFetched.Id);
                Console.WriteLine("     Name={0} ", newBookmarkFetched.Header);
                Console.WriteLine("     Desc={0} ", newBookmarkFetched.Description);
                Console.WriteLine("     user={0} ", newBookmarkFetched.User);
                Console.WriteLine("     Device={0} Start={1} Stop={2}  ", newBookmarkFetched.DeviceId,
                                  newBookmarkFetched.TimeBegin, newBookmarkFetched.TimeEnd);
            }
            else
            {
                Console.WriteLine("Sorry no bookmarks found");
            }

            Console.WriteLine("");

            #endregion

            #region Deleting bookmarks

            Console.WriteLine("Deleting 2 newly created bookmarks");
            scs.BookmarkDelete(loginInfo.Token, newBookmark.Id);
            Console.WriteLine("   -> first deleted");
            scs.BookmarkDelete(loginInfo.Token, newBookmark2.Id);
            Console.WriteLine("   -> second deleted");

            #endregion



            Console.WriteLine("");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
Exemple #26
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///     14-Oct-13 - New method to log the page request information in the database ...
        /// </summary>
        public static void LogPageRequestInDatabase(ConfigurationInfo ci, string applicationName, string aspSessionID, string uniqueSessionID,
                                                    string pageURL, DateTime pageRequestTime, double serverProcessingMS, int currentUserID, string ipAddress)
        {
            bool success = false;

            DatabaseWrapper dbInfo = null;

            try {
                //_____ Check for a null configurationInfo or dbConInfo object
                if (ci == null || ci.DbConInfo.NAME == null)
                {
                    Logger.LogError(200, "Error inserting the PageRequest log into the database - null configurationInfo found, probably because of an application reset or session timeout.");
                }
                else
                {
                    // 3-Mar-2016 - ignore specific IP addresses (e.g. robots like the UptimeRobot), as these are artificially bloating the logs with limited utility!
                    if (ipAddress == null || AddressesToIgnore.Contains(ipAddress) == false)
                    {
                        //_____ Check for s***e data and make it blank if so, so it doesn't kill the database ...
                        applicationName = (applicationName == null) ? "" : applicationName;
                        aspSessionID    = (aspSessionID == null) ? "" : aspSessionID;
                        uniqueSessionID = (uniqueSessionID == null) ? "" : uniqueSessionID;
                        pageURL         = (pageURL == null) ? "" : pageURL;

                        //_____ Connect to the database ...
                        dbInfo = new DatabaseWrapper(ci);
                        dbInfo.Connect();

                        //_____ Create the table if it does not already exist
                        string createTableSQL = @"
                    CREATE TABLE " + logTN + @" (
                        ID int NOT NULL Auto_Increment, PRIMARY KEY(ID),
                        Application_Name VARCHAR(255), INDEX Application_Name(Application_Name),
                        Session_ID_ASP VARCHAR(50), INDEX Session_ID_ASP(Session_ID_ASP),
                        Session_ID_Unique VARCHAR(50), INDEX Session_ID_Unique(Session_ID_Unique),
                        Page_Name VARCHAR(255), INDEX Page_Name(Page_Name),
                        Page_URL LONGTEXT,
                        Page_Request_Date DATETIME, INDEX Page_Request_Date(Page_Request_Date),
                        Server_Render_Speed DOUBLE, INDEX Server_Render_Speed(Server_Render_Speed),
                        Current_User_ID INT, INDEX Current_User_ID(Current_User_ID),
                        IP_Address	VARCHAR(20),    INDEX IP_Address(IP_Address)
                    ) ENGINE=MyISAM;
                ";

                        if (dbInfo.TableExists(logTN) == false)
                        {
                            dbInfo.ExecuteSQL(createTableSQL, ref success);
                        }

                        //_____ Parse the page name
                        string pageName = "";
                        {
                            // remove the ?...... page params
                            string[] bits1 = pageURL.Split(new string[] { "?", "&" }, StringSplitOptions.None);
                            string[] bits2 = bits1[0].Split(new string[] { "/", "\\" }, StringSplitOptions.None);
                            pageName = bits2[bits2.Length - 1];
                        }

                        //_____ Build the SQL and run the insert ...
                        StringBuilder sql = new StringBuilder();
                        sql.Append("INSERT INTO " + logTN
                                   + " (Application_Name, Session_ID_ASP, Session_ID_Unique, Page_Name, Page_URL, Page_Request_Date, Server_Render_Speed, Current_User_ID, IP_Address ) VALUES (");
                        sql.Append(DataUtilities.Quote(applicationName) + ", ");
                        sql.Append(DataUtilities.Quote(aspSessionID) + ", ");
                        sql.Append(DataUtilities.Quote(uniqueSessionID) + ", ");
                        sql.Append(DataUtilities.Quote(pageName) + ", ");
                        sql.Append(DataUtilities.Quote(pageURL) + ", ");
                        sql.Append(DataUtilities.Quote(DateTimeInformation.FormatDatabaseDate(pageRequestTime, true, true)) + ", ");
                        sql.Append(serverProcessingMS + ", ");
                        sql.Append(currentUserID + ", ");
                        sql.Append(DataUtilities.DatabaseifyString(ipAddress, false));

                        sql.Append(");");

                        int numInserts = dbInfo.ExecuteSQL(sql.ToString(), ref success);

                        if (success == false)
                        {
                            Logger.LogError(201, "Error inserting the PageRequest log into the database - check the detailed log for details.");
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.LogError(202, "Error inserting the PageRequest log into the database: " + ex.ToString());
            } finally {
                if (dbInfo != null)
                {
                    dbInfo.Disconnect();
                }
            }
        }
Exemple #27
0
        // OK clicked
        private void apply_Click(object sender, EventArgs e)
        {
            Configuration newcfg;
            WAD           sourcewad;
            bool          conflictingname;

            // Configuration selected?
            if (config.SelectedIndex == -1)
            {
                // Select a configuration!
                MessageBox.Show(this, "Please select a game configuration to use for editing your map.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                config.Focus();
                return;
            }

            // Level name empty?
            if (levelname.Text.Length == 0)
            {
                // Enter a level name!
                MessageBox.Show(this, "Please enter a level name for your map.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                levelname.Focus();
                return;
            }

            // Collect information
            ConfigurationInfo configinfo = General.Configs[config.SelectedIndex];
            DataLocationList  locations  = datalocations.GetResources();

            // When making a new map, check if we should warn the user for missing resources
            if (newmap && (locations.Count == 0) && (configinfo.Resources.Count == 0))
            {
                if (MessageBox.Show(this, "You are about to make a map without selecting any resources. Textures, flats and " +
                                    "sprites may not be shown correctly or may not show up at all. Do you want to continue?", Application.ProductName,
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            // Next checks are only for maps that are already opened
            if (!newmap)
            {
                // Now we check if the map name the user has given does already exist in the source WAD file
                // We have to warn the user about that, because it would create a level name conflict in the WAD

                // Level name changed and the map exists in a source wad?
                if ((levelname.Text != options.CurrentName) && (General.Map != null) &&
                    (General.Map.FilePathName != "") && File.Exists(General.Map.FilePathName))
                {
                    // Open the source wad file to check for conflicting name
                    sourcewad       = new WAD(General.Map.FilePathName, true);
                    conflictingname = (sourcewad.FindLumpIndex(levelname.Text) > -1);
                    sourcewad.Dispose();

                    // Names conflict?
                    if (conflictingname)
                    {
                        // Show warning!
                        if (General.ShowWarningMessage("The map name \"" + levelname.Text + "\" is already in use by another map or data lump in the source WAD file. Saving your map with this name will cause conflicting data lumps in the WAD file. Do you want to continue?", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2) == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                // When the user changed the configuration to one that has a different read/write interface,
                // we have to warn the user that the map may not be compatible.

                // Configuration changed?
                if ((options.ConfigFile != "") && (General.Configs[config.SelectedIndex].Filename != options.ConfigFile))
                {
                    // Load the new cfg file
                    newcfg = General.LoadGameConfiguration(General.Configs[config.SelectedIndex].Filename);
                    if (newcfg == null)
                    {
                        return;
                    }

                    // Check if the config uses a different IO interface
                    if (newcfg.ReadSetting("formatinterface", "") != General.Map.Config.FormatInterface)
                    {
                        // Warn the user about IO interface change
                        if (General.ShowWarningMessage("The game configuration you selected uses a different file format than your current map. Because your map was not designed for this format it may cause the map to work incorrectly in the game. Do you want to continue?", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2) == DialogResult.No)
                        {
                            // Reset to old configuration
                            for (int i = 0; i < config.Items.Count; i++)
                            {
                                // Is this configuration the old config?
                                if (string.Compare(General.Configs[i].Filename, options.ConfigFile, true) == 0)
                                {
                                    // Select this item
                                    config.SelectedIndex = i;
                                }
                            }
                            return;
                        }
                    }
                }
            }

            // Apply changes
            options.ClearResources();
            options.ConfigFile    = General.Configs[config.SelectedIndex].Filename;
            options.CurrentName   = levelname.Text.Trim().ToUpper();
            options.StrictPatches = strictpatches.Checked;
            options.CopyResources(datalocations.GetResources());

            // Reset default drawing textures
            General.Settings.DefaultTexture        = null;
            General.Settings.DefaultFloorTexture   = null;
            General.Settings.DefaultCeilingTexture = null;

            // Hide window
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        /// <summary>
        /// Exports the configuration to the specified file path.
        /// </summary>
        /// <param name="configurationId">The configuration identifier.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public bool ExportConfiguration(Guid configurationId, string filePath, string userName)
        {
            var configuration = GetConfiguration(configurationId, userName) as BaseConfiguration;
            if (configuration == null) return false;

            var configData = new ConfigurationInfo
            {
                Version = CurrentVersion,
                Content = configuration.SerializeToXml()
            };

            configData.SerializeToFile(filePath);

            return true;
        }
        public MigrationConfiguration(XmlNode section)
        {
            //Convert the XmlNode to an XDocument (for LINQ).
            XDocument xmlDoc = XDocument.Parse(section.OuterXml);

            // **********************************
            // * V1 source connection.
            // **********************************
            var v1Source = from item in xmlDoc.Descendants("V1SourceConnection")
                           select new ConnectionInfo
                           {
                               Url = item.Element("Url").Value,
                               Username = string.IsNullOrEmpty(item.Element("Username").Value) ? string.Empty : item.Element("Username").Value,
                               Password = string.IsNullOrEmpty(item.Element("Password").Value) ? string.Empty : item.Element("Password").Value,
                               Project = string.IsNullOrEmpty(item.Element("Project").Value) ? string.Empty : item.Element("Project").Value,
                               AuthenticationType = string.IsNullOrEmpty(item.Attribute("authenticationType").Value) ? string.Empty : item.Attribute("authenticationType").Value
                           };
            if (v1Source.Count() == 0)
                throw new ConfigurationErrorsException("Missing V1SourceConnection information in application config file.");
            else
                V1SourceConnection = v1Source.First();

            // **********************************
            // * V1 target connection.
            // **********************************
            var v1Target = from item in xmlDoc.Descendants("V1TargetConnection")
                           select new ConnectionInfo
                           {
                               Url = item.Element("Url").Value,
                               Username = string.IsNullOrEmpty(item.Element("Username").Value) ? string.Empty : item.Element("Username").Value,
                               Password = string.IsNullOrEmpty(item.Element("Password").Value) ? string.Empty : item.Element("Password").Value,
                               Project = string.IsNullOrEmpty(item.Element("Project").Value) ? string.Empty : item.Element("Project").Value,
                               AuthenticationType = string.IsNullOrEmpty(item.Attribute("authenticationType").Value) ? string.Empty : item.Attribute("authenticationType").Value
                           };
            if (v1Target.Count() == 0)
                throw new ConfigurationErrorsException("Missing V1TargetConnection information in application config file.");
            else
                V1TargetConnection = v1Target.First();

            // **********************************
            // * V1 staging database.
            // **********************************
            var v1Database = from item in xmlDoc.Descendants("V1StagingDatabase")
                             select new StagingDatabaseInfo
                             {
                               Server = item.Element("Server").Value,
                               Database = item.Element("Database").Value,
                               Username = string.IsNullOrEmpty(item.Element("Username").Value) ? string.Empty : item.Element("Username").Value,
                               Password = string.IsNullOrEmpty(item.Element("Password").Value) ? string.Empty : item.Element("Password").Value,
                               TrustedConnection = System.Convert.ToBoolean(item.Attribute("trustedConnection").Value)
                             };
            if (v1Database.Count() == 0)
                throw new ConfigurationErrorsException("Missing V1StagingDatabase information in application config file.");
            else
                V1StagingDatabase = v1Database.First();

            // **********************************
            // * Rally source connection.
            // **********************************
            var rallySource = from item in xmlDoc.Descendants("RallySourceConnection")
                              select new RallyConnectionInfo
                              {
                                Url = item.Element("url").Value,
                                Username = string.IsNullOrEmpty(item.Element("username").Value) ? string.Empty : item.Element("username").Value,
                                Password = string.IsNullOrEmpty(item.Element("password").Value) ? string.Empty : item.Element("password").Value,
                                ExportFileDirectory = item.Element("exportFileDirectory").Value,
                                UserExportFilePrefix = item.Element("userExportFilePrefix").Value,
                                ProjectExportFilePrefix = item.Element("projectExportFilePrefix").Value,
                                ReleaseExportFilePrefix = item.Element("releaseExportFilePrefix").Value,
                                IterationExportFilePrefix = item.Element("iterationExportFilePrefix").Value,
                                EpicExportFilePrefix = item.Element("epicExportFilePrefix").Value,
                                StoryExportFilePrefix = item.Element("storyExportFilePrefix").Value,
                                DefectExportFilePrefix = item.Element("defectExportFilePrefix").Value,
                                TaskExportFilePrefix = item.Element("taskExportFilePrefix").Value,
                                TestExportFilePrefix = item.Element("testExportFilePrefix").Value,
                                RegressionTestExportFilePrefix = item.Element("regressiontestExportFilePrefix").Value,
                                TestStepExportFilePrefix = item.Element("teststepExportFilePrefix").Value,
                                ConversationExportFilePrefix = item.Element("conversationExportFilePrefix").Value,
                                OrphanedTestProject = item.Element("orphanedTestProject").Value
                              };
            RallySourceConnection = rallySource.First();

            // **********************************
            // * Jira Configuration.
            // **********************************
            var jiraConfig = from item in xmlDoc.Descendants("JiraConfiguration")
                           select new JiraConfigurationInfo
                           {
                               XmlFileName = item.Element("xmlFileName").Value,
                               ProjectName = item.Element("projectName").Value,
                               ProjectDescription = item.Element("projectDescription").Value,
                               DefaultSchedule = item.Element("defaultSchedule").Value,
                               JiraUrl = item.Element("jiraUrl").Value,
                               StoryIssueTypes = string.IsNullOrEmpty(item.Element("storyIssueTypes").Value) ? string.Empty : item.Element("storyIssueTypes").Value,
                               DefectIssueTypes = string.IsNullOrEmpty(item.Element("defectIssueTypes").Value) ? string.Empty : item.Element("defectIssueTypes").Value,
                               EpicIssueTypes = string.IsNullOrEmpty(item.Element("epicIssueTypes").Value) ? string.Empty : item.Element("epicIssueTypes").Value,
                               IssueIssueTypes = string.IsNullOrEmpty(item.Element("issueIssueTypes").Value) ? string.Empty : item.Element("issueIssueTypes").Value,
                               RequestIssueTypes = string.IsNullOrEmpty(item.Element("requestIssueTypes").Value) ? string.Empty : item.Element("requestIssueTypes").Value,
                               TaskIssueTypes = string.IsNullOrEmpty(item.Element("taskIssueTypes").Value) ? string.Empty : item.Element("taskIssueTypes").Value,
                               JiraTeamReference = string.IsNullOrEmpty(item.Element("jiraTeamReference").Value) ? string.Empty : item.Element("jiraTeamReference").Value,
                               JiraBacklogGroupReference = string.IsNullOrEmpty(item.Element("jiraBacklogGroupReference").Value) ? string.Empty : item.Element("jiraBacklogGroupReference").Value,
                               JiraBacklogGoalReference = string.IsNullOrEmpty(item.Element("jiraBacklogGoalReference").Value) ? string.Empty : item.Element("jiraBacklogGoalReference").Value
                           };
            if (jiraConfig.Count() == 0)
                throw new ConfigurationErrorsException("Missing JiraConfiguration information in application config file.");
            else
                JiraConfiguration = jiraConfig.First();

            // **********************************
            // * General configurations.
            // **********************************
            var v1Config = from item in xmlDoc.Descendants("configurations")
                           select new ConfigurationInfo
                           {
                               SourceConnectionToUse = item.Element("sourceConnectionToUse").Value,
                               PerformExport = System.Convert.ToBoolean(item.Element("performExport").Value),
                               PerformImport = System.Convert.ToBoolean(item.Element("performImport").Value),
                               PerformClose = System.Convert.ToBoolean(item.Element("performClose").Value),
                               PerformCleanup = System.Convert.ToBoolean(item.Element("performCleanup").Value),
                               MigrateTemplates = System.Convert.ToBoolean(item.Element("migrateTemplates").Value),
                               MigrateAttachmentBinaries = System.Convert.ToBoolean(item.Element("migrateAttachmentBinaries").Value),
                               MigrateProjectMembership = System.Convert.ToBoolean(item.Element("migrateProjectMembership").Value),
                               MigrateDuplicateSchedules = System.Convert.ToBoolean(item.Element("migrateDuplicateSchedules").Value),
                               UseNPIMasking = System.Convert.ToBoolean(item.Element("useNPIMasking").Value),
                               MergeRootProjects = System.Convert.ToBoolean(item.Element("mergeRootProjects").Value),
                               AddV1IDToTitles = System.Convert.ToBoolean(item.Element("addV1IDToTitles").Value),
                               PageSize = System.Convert.ToInt32(item.Element("pageSize").Value),
                               CustomV1IDField = string.IsNullOrEmpty(item.Element("customV1IDField").Value) ? string.Empty : item.Element("customV1IDField").Value,
                               ImportAttachmentsAsLinksURL = string.IsNullOrEmpty(item.Element("importAttachmentsAsLinksURL").Value) ? string.Empty : item.Element("importAttachmentsAsLinksURL").Value,
                               SetAllMembershipToRoot = System.Convert.ToBoolean(item.Element("setAllMembershipToRoot").Value),
                               SourceListTypeValue = string.IsNullOrEmpty(item.Element("sourceListTypeValue").Value) ? string.Empty : item.Element("sourceListTypeValue").Value,
                               MigrateUnauthoredConversationsAsAdmin = System.Convert.ToBoolean(item.Element("migrateUnauthoredConversationsAsAdmin").Value),
                               LogExceptions = System.Convert.ToBoolean(item.Element("logExceptions").Value)
                           };
            if (v1Config.Count() == 0)
                throw new ConfigurationErrorsException("Missing general configuration information in application config file.");
            else
                V1Configurations = v1Config.First();

            // **********************************
            // * Assets to migrate.
            // **********************************
            var assetData = from item in xmlDoc.Descendants("asset")
                            select item;
            if (assetData.Count() == 0)
                throw new ConfigurationErrorsException("Missing assets to migrate information in application config file.");

            foreach (var asset in assetData)
            {
                AssetInfo assetInfo = new AssetInfo();
                assetInfo.Name = asset.Attribute("name").Value;
                assetInfo.InternalName = asset.Attribute("internalName").Value;
                assetInfo.Enabled = System.Convert.ToBoolean(asset.Attribute("enabled").Value);
                assetInfo.DuplicateCheckField = asset.Attribute("duplicateCheckField").Value;
                assetInfo.EnableCustomFields = System.Convert.ToBoolean(asset.Attribute("enableCustomFields").Value);
                AssetsToMigrate.Add(assetInfo);
            }

            // **********************************
            // * List types to migrate.
            // **********************************
            var listTypeData = from item in xmlDoc.Descendants("listType")
                               select item;
            if (listTypeData.Count() == 0)
                throw new ConfigurationErrorsException("Missing list types to migrate information in application config file.");

            foreach (var listType in listTypeData)
            {
                ListTypeInfo listTypeInfo = new ListTypeInfo();
                listTypeInfo.Name = listType.Attribute("name").Value;
                listTypeInfo.Enabled = System.Convert.ToBoolean(listType.Attribute("enabled").Value);
                ListTypesToMigrate.Add(listTypeInfo);
            }

            // **********************************
            // * List Values
            // **********************************
            var listValueData = from item in xmlDoc.Descendants("listValue") select item;

            foreach (var listValue in listValueData)
            {
                ListValueInfo listValueInfo = new ListValueInfo();
                listValueInfo.AssetType = listValue.Attribute("assetType").Value;
                listValueInfo.FieldName = listValue.Attribute("fieldName").Value;
                listValueInfo.ListName = listValue.Attribute("listName").Value;
                listValueInfo.OldValue = listValue.Attribute("oldValue").Value;
                listValueInfo.NewValue = listValue.Attribute("newValue").Value;
                ListValues.Add(listValueInfo);
            }

            // **********************************
            // * Custom fields to migrate.
            // **********************************
            var customFieldData = from item in xmlDoc.Descendants("customField")
                                  select item;
            if (customFieldData.Count() == 0)
                throw new ConfigurationErrorsException("Missing custom fields to migrate information in application config file.");

            foreach (var customField in customFieldData)
            {
                CustomFieldInfo customFieldInfo = new CustomFieldInfo();
                customFieldInfo.SourceName = customField.Attribute("sourceName").Value;
                customFieldInfo.TargetName = customField.Attribute("targetName").Value;
                customFieldInfo.AssetType = customField.Attribute("assetType").Value;
                customFieldInfo.DataType = customField.Attribute("dataType").Value;
                customFieldInfo.RelationName = customField.Attribute("relationName").Value;
                CustomFieldsToMigrate.Add(customFieldInfo);
            }
        }
Exemple #30
0
 /// <summary>
 /// This is a copy constructor, used primarily for get-command.
 /// </summary>
 internal ConfigurationInfo(string name, ConfigurationInfo other)
     : base(name, other)
 {
 }
Exemple #31
0
 /// <summary>
 /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
 /// sets based on an argument list (so we can get the dynamic parameters.)
 /// </summary>
 internal override CommandInfo CreateGetCommandCopy(object[] arguments)
 {
     var copy = new ConfigurationInfo(this) { IsGetCommandCopy = true, Arguments = arguments };
     return copy;
 }
Exemple #32
0
 public UserAdministration(ConfigurationInfo lcf)
 {
     this.Lcf           = lcf;
     SecurityOperations = new BaseSecurityOperations(lcf);
 }
Exemple #33
0
        public void CompareModule()
        {
            Dictionary <string, EnvVal> goodEnv = new Dictionary <string, EnvVal>();
            Dictionary <string, EnvVal> newEnv  = new Dictionary <string, EnvVal> {
                ["a"] = new EnvVal("B")
            };
            IList <string> dockerEnv = new List <string> {
                "c=d"
            };
            KubernetesConfig goodConfig     = new KubernetesConfig("image:tag", CreateOptions(), Option.None <AuthConfig>());
            KubernetesConfig imageDifferent = new KubernetesConfig("image:newtag", CreateOptions(), Option.None <AuthConfig>());

            var auth1 = new AuthConfig("secret1");
            KubernetesConfig auth1Config = new KubernetesConfig("image:tag", CreateOptions(), Option.Some(auth1));

            var auth2 = new AuthConfig("secret2");
            KubernetesConfig auth2Config = new KubernetesConfig("image:tag", CreateOptions(), Option.Some(auth2));

            var auth3 = new AuthConfig("secret3");
            KubernetesConfig auth3Config = new KubernetesConfig("image:tag", CreateOptions(), Option.Some(auth3));

            var auth4 = new AuthConfig("secret4");
            KubernetesConfig auth4Config = new KubernetesConfig("image:tag", CreateOptions(), Option.Some(auth4));

            KubernetesConfig createContainerConfigDifferent = new KubernetesConfig("image:tag", CreateOptions(dockerEnv), Option.None <AuthConfig>());

            ConfigurationInfo goodInfo = new ConfigurationInfo(string.Empty);

            var m1 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);
            var m2 = new KubernetesModule("name2", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);

            var m3 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);
            var m4 = new KubernetesModule("name1", "v2", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);

            var m5 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);
            var m6 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Stopped, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);

            var m7 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);
            var m8 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Never, goodInfo, goodEnv, goodConfig, ImagePullPolicy.OnCreate);

            var m9  = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, imageDifferent, ImagePullPolicy.OnCreate);
            var m10 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, auth1Config, ImagePullPolicy.OnCreate);
            var m11 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, auth2Config, ImagePullPolicy.OnCreate);
            var m12 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, auth3Config, ImagePullPolicy.OnCreate);
            var m13 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, auth4Config, ImagePullPolicy.OnCreate);
            var m14 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, goodEnv, createContainerConfigDifferent, ImagePullPolicy.OnCreate);

            var m15 = new KubernetesModule("name1", "v1", "docker", ModuleStatus.Running, RestartPolicy.Always, goodInfo, newEnv, goodConfig, ImagePullPolicy.OnCreate);

            Assert.NotEqual(m1, m2);
            Assert.NotEqual(m3, m4);
            Assert.NotEqual(m5, m6);
            Assert.NotEqual(m7, m8);
            Assert.NotEqual(m1, m9);
            Assert.NotEqual(m9, m1);
            Assert.NotEqual(m10, m9);
            Assert.NotEqual(m9, m10);
            Assert.NotEqual(m10, m11);
            Assert.NotEqual(m11, m10);
            Assert.NotEqual(m10, m12);
            Assert.NotEqual(m10, m13);
            Assert.NotEqual(m11, m14);
            Assert.NotEqual(m11, m15);

            Assert.True(m5.IsOnlyModuleStatusChanged(m6));

            Assert.False(m1.IsOnlyModuleStatusChanged(m2));
            Assert.False(m1.IsOnlyModuleStatusChanged(m9));
        }
Exemple #34
0
        public async Task EdgeHubLaunch()
        {
            const string Image                = "hello-world:latest";
            const string Name                 = Constants.EdgeHubModuleName;
            string       sharedAccessKey      = Convert.ToBase64String(Encoding.UTF8.GetBytes("test"));
            string       fakeConnectionString = $"Hostname=fakeiothub;Deviceid=test;SharedAccessKey={sharedAccessKey}";

            try
            {
                using (var cts = new CancellationTokenSource(this.defaultTimeout))
                {
                    var mountMap = new Dictionary <string, string>()
                    {
                        { Constants.EdgeModuleCaCertificateFileKey, "/module.ca.cert" },
                        { Constants.EdgeModuleHubServerCaChainCertificateFileKey, "/module.ca.chain.cert" },
                        { Constants.EdgeModuleHubServerCertificateFileKey, "/module.server.cert" }
                    };
                    await DockerHelper.Client.CleanupContainerAsync(Name, Image);

                    // ensure image has been pulled
                    await DockerHelper.Client.PullImageAsync(Image, cts.Token);

                    var dockerLoggingOptions = new Dictionary <string, string>
                    {
                        { "max-size", "1m" },
                        { "max-file", "1" }
                    };
                    var loggingConfig = new DockerLoggingConfig("json-file", dockerLoggingOptions);
                    // Logging options will be derived from module options.
                    var config            = new DockerConfig(Image, @"{""Env"": [""k1=v1"", ""k2=v2""], ""HostConfig"": {""LogConfig"": {""Type"":""none""}, ""PortBindings"": {""8080/tcp"": [{""HostPort"": ""80""}],""443/tcp"": [{""HostPort"": ""11443""}]}}}", Option.None <string>());
                    var configurationInfo = new ConfigurationInfo();
                    var module            = new EdgeHubDockerModule("docker", ModuleStatus.Running, global::Microsoft.Azure.Devices.Edge.Agent.Core.RestartPolicy.Always, config, ImagePullPolicy.Never, Constants.HighestPriority, configurationInfo, EnvVars);

                    IConfigurationRoot configRoot = new ConfigurationBuilder().AddInMemoryCollection(
                        new Dictionary <string, string>
                    {
                        { "EdgeHubConnectionString", fakeConnectionString },
                        { Constants.NetworkIdKey, "testnetwork" },
                        { Constants.EdgeDeviceHostNameKey, "testdevice" },
                        { Constants.EdgeModuleHubServerCaChainCertificateFileKey, mountMap[Constants.EdgeModuleHubServerCaChainCertificateFileKey] },
                        { Constants.EdgeModuleHubServerCertificateFileKey, mountMap[Constants.EdgeModuleHubServerCertificateFileKey] },
                    }).Build();
                    var modules = new Dictionary <string, IModule> {
                        [Name] = module
                    };
                    var systemModules        = new SystemModules(null, null);
                    var deploymentConfigInfo = new DeploymentConfigInfo(1, new DeploymentConfig("1.0", new DockerRuntimeInfo("docker", new DockerRuntimeConfig("1.25", string.Empty)), systemModules, modules, null));
                    var configSource         = new Mock <IConfigSource>();
                    configSource.Setup(cs => cs.Configuration).Returns(configRoot);
                    configSource.Setup(cs => cs.GetDeploymentConfigInfoAsync()).ReturnsAsync(deploymentConfigInfo);

                    var identity = new Mock <IModuleIdentity>();
                    identity.Setup(id => id.Credentials).Returns(new ConnectionStringCredentials(fakeConnectionString));

                    ICommand command = await CreateCommand.BuildAsync(DockerHelper.Client, module, identity.Object, loggingConfig, configSource.Object, true);

                    // run the command
                    await command.ExecuteAsync(cts.Token);

                    // verify container is created with correct settings
                    ContainerInspectResponse container = await DockerHelper.Client.Containers.InspectContainerAsync(Name);

                    Assert.Equal(Name, container.Name.Substring(1)); // for whatever reason the container name is returned with a starting "/"
                    // edgeHub doesn't have a version
                    Assert.Equal("missing", container.Config.Labels.GetOrElse(Constants.Labels.Version, "missing"));
                    // port bindings - added default bindings for edgeHub
                    Assert.True(container.HostConfig.PortBindings.ContainsKey("8080/tcp"));
                    Assert.True(container.HostConfig.PortBindings.ContainsKey("8883/tcp"));
                    Assert.Equal("8883", container.HostConfig.PortBindings["8883/tcp"].First().HostPort);
                    Assert.True(container.HostConfig.PortBindings.ContainsKey("443/tcp"));
                    Assert.True(container.HostConfig.PortBindings["443/tcp"].Count == 2);
                    Assert.Equal("11443", container.HostConfig.PortBindings["443/tcp"][0].HostPort);
                    Assert.Equal("443", container.HostConfig.PortBindings["443/tcp"][1].HostPort);
                    // logging
                    Assert.Equal("none", container.HostConfig.LogConfig.Type);
                    Assert.True(container.HostConfig.LogConfig.Config.Count == 0);
                    // network settings
                    Assert.Equal("testdevice", container.NetworkSettings.Networks.GetOrElse("testnetwork", new EndpointSettings()).Aliases.FirstOrDefault());

                    Assert.Equal("testdevice", container.NetworkSettings.Networks.GetOrElse("testnetwork", new EndpointSettings()).Aliases.FirstOrDefault());
                    // environment variables
                    IDictionary <string, string> envMap = container.Config.Env.ToDictionary('=');
                    Assert.Equal("v1", envMap["k1"]);
                    Assert.Equal("v2", envMap["k2"]);
                    Assert.Equal(fakeConnectionString, envMap[Constants.IotHubConnectionStringKey]);
                    // certificates env variables
                    Assert.Equal("/module.ca.chain.cert", envMap[Constants.EdgeModuleHubServerCaChainCertificateFileKey]);
                    Assert.Equal("/module.server.cert", envMap[Constants.EdgeModuleHubServerCertificateFileKey]);
                }
            }
            finally
            {
                await DockerHelper.Client.CleanupContainerAsync(Name, Image);
            }
        }
Exemple #35
0
        public static List <EntityMetadata> GetAllEntities(IOrganizationService service, ConfigurationInfo config)
        {
            // retrieve all entities (just entity metadata)
            var req = new RetrieveAllEntitiesRequest()
            {
                EntityFilters         = EntityFilters.Entity,
                RetrieveAsIfPublished = config.RetrieveAsIfPublished
            };
            var resp = (RetrieveAllEntitiesResponse)service.Execute(req);

            // set the itemsource of the itembox equal to entity metadata that is customizable (takes out systemjobs and stuff like that)
            var entities = resp.EntityMetadata.Where(x => x.IsCustomizable.Value == true).ToList <EntityMetadata>();

            return(entities);
        }
 public NonDockerModule(string name, string version, string type, ModuleStatus desiredStatus, global::Microsoft.Azure.Devices.Edge.Agent.Core.RestartPolicy restartPolicy, ImagePullPolicy imagePullPolicy, ConfigurationInfo configurationInfo, IDictionary <string, EnvVal> env, string config)
 {
     this.Name              = name;
     this.Version           = version;
     this.Type              = type;
     this.DesiredStatus     = desiredStatus;
     this.RestartPolicy     = restartPolicy;
     this.ImagePullPolicy   = imagePullPolicy;
     this.ConfigurationInfo = configurationInfo;
     this.Env    = env;
     this.Config = config;
 }
Exemple #37
0
        public static EntityMetadata RetrieveEntityAttributeMeta(IOrganizationService service, ConfigurationInfo config, string logicalName)
        {
            // Retrieve the attribute metadata
            var req = new RetrieveEntityRequest()
            {
                LogicalName           = logicalName,
                EntityFilters         = EntityFilters.Attributes,
                RetrieveAsIfPublished = config.RetrieveAsIfPublished
            };
            var resp = (RetrieveEntityResponse)service.Execute(req);

            return(resp.EntityMetadata);
        }
 public EdgeAgentDockerModule(string type, DockerConfig settings, ConfigurationInfo configuration, IDictionary <string, EnvVal> env, string version = "")
     : base(Core.Constants.EdgeAgentModuleName, version, ModuleStatus.Running, RestartPolicy.Always, settings, configuration, env)
 {
     Preconditions.CheckArgument(type?.Equals("docker") ?? false);
 }
        // Configuration is selected
        private void config_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Anything selected?
            if (config.SelectedIndex < 0)
            {
                return;
            }

            // Keep selected name, if any
            string selectedname = (mapslist.SelectedItems.Count > 0 ? mapslist.SelectedItems[0].Text : "");

            // Make an array for the map names
            //List<ListViewItem> mapnames = new List<ListViewItem>();
            // [ZZ] This should be a string list so we can do mapnames.Contains
            List <string> mapnames = new List <string>();

            // Get selected configuration info
            ConfigurationInfo ci = (config.SelectedItem as ConfigurationInfo);

            //mxd. Get configuration
            Configuration cfg = ci.Configuration;

            // Get the map lump names
            IDictionary maplumpnames = cfg.ReadSetting("maplumpnames", new Hashtable());

            // Count how many required lumps we have to find
            int lumpsrequired = 0;

            foreach (DictionaryEntry ml in maplumpnames)
            {
                // Ignore the map header (it will not be found because the name is different)
                if (ml.Key.ToString() != MapManager.CONFIG_MAP_HEADER)
                {
                    // Read lump setting and count it
                    if (cfg.ReadSetting("maplumpnames." + ml.Key + ".required", false))
                    {
                        lumpsrequired++;
                    }
                }
            }

            // Go for all the lumps in the wad
            for (int scanindex = 0; scanindex < (wadfile.Lumps.Count - 1); scanindex++)
            {
                // Make sure this lump is not part of the map.
                if (!maplumpnames.Contains(wadfile.Lumps[scanindex].Name))
                {
                    // Reset check
                    int lumpsfound  = 0;
                    int checkoffset = 1;

                    // Continue while still within bounds and lumps are still recognized
                    while (((scanindex + checkoffset) < wadfile.Lumps.Count) &&
                           maplumpnames.Contains(wadfile.Lumps[scanindex + checkoffset].Name))
                    {
                        string lumpname = wadfile.Lumps[scanindex + checkoffset].Name;
                        //mxd. Lump cannot present in current map format, fail this check
                        if (cfg.ReadSetting("maplumpnames." + lumpname + ".forbidden", false))
                        {
                            lumpsfound = -1;
                            break;
                        }

                        // Count the lump when it is marked as required
                        if (cfg.ReadSetting("maplumpnames." + lumpname + ".required", false))
                        {
                            lumpsfound++;
                        }

                        // Check the next lump
                        checkoffset++;
                    }

                    // Map found? Then add it to the list
                    string mapname = wadfile.Lumps[scanindex].Name;
                    if ((lumpsfound >= lumpsrequired) && !mapnames.Contains(mapname))
                    {
                        mapnames.Add(mapname);
                    }
                }
            }

            // Clear the list and add the new map names
            mapslist.BeginUpdate();
            mapslist.Items.Clear();
            foreach (string mapname in mapnames)
            {
                mapslist.Items.Add(mapname);
            }
            mapslist.Sort();

            // Go for all items in the list
            foreach (ListViewItem item in mapslist.Items)
            {
                // Was this item previously selected?
                if (item.Text == selectedname)
                {
                    // Select it again
                    item.Selected = true;
                    break;
                }
            }
            if ((mapslist.SelectedItems.Count == 0) && (mapslist.Items.Count > 0))
            {
                mapslist.Items[0].Selected = true;
            }
            mapslist.EndUpdate();

            //mxd. Disable script compiler selector when there are no maps detected using current configuration
            if (mapslist.Items.Count == 0)
            {
                scriptcompiler.Enabled       = false;
                scriptcompiler.SelectedIndex = -1;
                scriptcompilerlabel.Enabled  = false;
            }

            // Show configuration resources
            datalocations.FixedResourceLocationList(ci.Resources);

            // Update long texture names checkbox (mxd)
            longtexturenames.Enabled = cfg.ReadSetting("longtexturenames", false);
            longtexturenames.Checked = (longtexturenames.Enabled && options != null && options.UseLongTextureNames);

            // Update resource usage
            readonlyresources.Checked = (options != null && options.UseResourcesInReadonlyMode);
        }
Exemple #40
0
        public async Task EdgeHubLaunchWithBadLogOptions()
        {
            const string Image                = "hello-world:latest";
            const string Name                 = Constants.EdgeHubModuleName;
            string       sharedAccessKey      = Convert.ToBase64String(Encoding.UTF8.GetBytes("test"));
            string       fakeConnectionString = $"Hostname=fakeiothub;Deviceid=test;SharedAccessKey={sharedAccessKey}";

            try
            {
                using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)))
                {
                    await DockerHelper.Client.CleanupContainerAsync(Name, Image);

                    // ensure image has been pulled
                    await DockerHelper.Client.PullImageAsync(Image, cts.Token);

                    var dockerLoggingOptions = new Dictionary <string, string>
                    {
                        { "max-size", "1m" },
                        { "max-file", "1" }
                    };
                    var loggingConfig     = new DockerLoggingConfig("json-file", dockerLoggingOptions);
                    var config            = new DockerConfig(Image, @"{""Env"": [""k1=v1"", ""k2=v2""]}");
                    var configurationInfo = new ConfigurationInfo("43");
                    var module            = new EdgeHubDockerModule("docker", ModuleStatus.Running, Core.RestartPolicy.Always, config, configurationInfo, EnvVars);

                    IConfigurationRoot configRoot = new ConfigurationBuilder().AddInMemoryCollection(
                        new Dictionary <string, string>
                    {
                        { "EdgeHubConnectionString", fakeConnectionString }
                    }).Build();
                    var modules = new Dictionary <string, IModule> {
                        [Name] = module
                    };
                    var systemModules        = new SystemModules(null, null);
                    var deploymentConfigInfo = new DeploymentConfigInfo(1, new DeploymentConfig("1.0", new DockerRuntimeInfo("docker", new DockerRuntimeConfig("1.25", "Not a valid JSON")), systemModules, modules));
                    var configSource         = new Mock <IConfigSource>();
                    configSource.Setup(cs => cs.Configuration).Returns(configRoot);
                    configSource.Setup(cs => cs.GetDeploymentConfigInfoAsync()).ReturnsAsync(deploymentConfigInfo);

                    var identity = new Mock <IModuleIdentity>();
                    identity.Setup(id => id.Credentials).Returns(new ConnectionStringCredentials(fakeConnectionString));

                    ICommand command = await CreateCommand.BuildAsync(DockerHelper.Client, module, identity.Object, loggingConfig, configSource.Object, true);

                    // run the command
                    await command.ExecuteAsync(cts.Token);

                    // verify container is created with correct settings
                    ContainerInspectResponse container = await DockerHelper.Client.Containers.InspectContainerAsync(Name);

                    Assert.Equal(Name, container.Name.Substring(1));  // for whatever reason the container name is returned with a starting "/"
                    // labels - edgeHub doesn's have a version
                    Assert.Equal("missing", container.Config.Labels.GetOrElse(Constants.Labels.Version, "missing"));
                    Assert.Equal("43", container.Config.Labels.GetOrElse(Constants.Labels.ConfigurationId, "missing"));
                    // port bindings - check that we added default bindings for hub
                    Assert.True(container.HostConfig.PortBindings.ContainsKey("8883/tcp"));
                    Assert.True(container.HostConfig.PortBindings["8883/tcp"].Count == 1);
                    Assert.Equal("8883", container.HostConfig.PortBindings["8883/tcp"].First().HostPort);
                    Assert.True(container.HostConfig.PortBindings.ContainsKey("443/tcp"));
                    Assert.True(container.HostConfig.PortBindings["443/tcp"].Count == 1);
                    Assert.Equal("443", container.HostConfig.PortBindings["443/tcp"][0].HostPort);
                    // logging
                    Assert.Equal("json-file", container.HostConfig.LogConfig.Type);
                    Assert.True(container.HostConfig.LogConfig.Config.Count == 2);
                    Assert.Equal("1m", container.HostConfig.LogConfig.Config.GetOrElse("max-size", "missing"));
                    Assert.Equal("1", container.HostConfig.LogConfig.Config.GetOrElse("max-file", "missing"));
                    // environment variables
                    IDictionary <string, string> envMap = container.Config.Env.ToDictionary('=');
                    Assert.Equal("v1", envMap["k1"]);
                    Assert.Equal("v2", envMap["k2"]);
                    Assert.Equal(fakeConnectionString, envMap[Constants.IotHubConnectionStringKey]);
                }
            }
            finally
            {
                await DockerHelper.Client.CleanupContainerAsync(Name, Image);
            }
        }
Exemple #41
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                    ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                    )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(true, false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName = Path.GetFileNameWithoutExtension(modulePath);
                    var modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, 
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                        case CommandTypes.Alias:
                                            current = new AliasInfo(entry.Value.Name, null, context);
                                            break;
                                        case CommandTypes.Workflow:
                                            current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Function:
                                            current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Filter:
                                            current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Configuration:
                                            current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Cmdlet:
                                            current = new CmdletInfo(entry.Value.Name, null, null, null, context);
                                            break;
                                        default:
                                            Dbg.Assert(false, "cannot be hit");
                                            break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return current;
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null) { continue; }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow)
                                {
                                    yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }