internal void Load(IDictionary envVariables)
 {
     Data = envVariables
         .Cast<DictionaryEntry>()
         .SelectMany(AzureEnvToAppEnv)
         .Where(entry => ((string)entry.Key).StartsWith(_prefix, StringComparison.OrdinalIgnoreCase))
         .ToDictionary(
             entry => ((string)entry.Key).Substring(_prefix.Length),
             entry => (string)entry.Value,
             StringComparer.OrdinalIgnoreCase);
 }
        public void GetEnumerator_LinqOverDictionaryEntries_Success(EnvironmentVariableTarget?target)
        {
            IDictionary envVars = target != null?
                                  Environment.GetEnvironmentVariables(target.Value) :
                                      Environment.GetEnvironmentVariables();

            Assert.IsType <Hashtable>(envVars);

            foreach (KeyValuePair <string, string> envVar in envVars.Cast <DictionaryEntry>().Select(de => new KeyValuePair <string, string>((string)de.Key, (string)de.Value)))
            {
                Assert.NotNull(envVar.Key);
            }
        }
        private static void CreateDictionaryKVAndTest(ReflectionsUtilsStrategy strategy, Type dictionaryType, params int[] args)
        {
            if (!TrySetStrategy(strategy))
            {
                return;
            }

            IFunctionCallback <int[], IEnumerable> dictionaryActivator = ReflectionUtils.CreateDictionary(dictionaryType.GetGenericTypeDefinition(), dictionaryType.GetGenericArguments()[0], dictionaryType.GetGenericArguments()[1], args.Length);
            IDictionary dictionary = dictionaryActivator.Invoke(args) as IDictionary;

            Assert.NotNull(dictionary);
            Assert.AreEqual(0, dictionary.Cast <object>().Count());
        }
        public IReadOnlyDictionary <string, string> List(EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
        {
            IDictionary source = Environment.GetEnvironmentVariables();
            IDictionary <string, string> results = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            // cannot use ToDictionary() because keys (names of env var) may duplicate on Linux,
            // with case being the only difference
            foreach (var item in source.Cast <DictionaryEntry>())
            {
                results[item.Key.ToString()] = item.Value.ToString();
            }
            return(new ReadOnlyDictionary <string, string>(results));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Converte o dicionario em uma coleção de parâmetros nome/valor.
        /// </summary>
        /// <param name="dictionary">O dicionário a ser convertido.</param>
        /// <returns>O mapa de parâmetros obtido.</returns>
        private static IDictionary <string, object> CreateMap(IDictionary dictionary)
        {
            var map = dictionary as IDictionary <string, object>;

            if (map == null)
            {
                var entries =
                    dictionary
                    .Cast <DictionaryEntry>()
                    .Select(e => new KeyValuePair <string, object>(e.Key.ToString(), e.Value));
                map = new HashMap(entries);
            }
            return(map);
        }
Ejemplo n.º 6
0
        private bool?CompareDictionary(IDictionary source, IDictionary destination)
        {
            if (source == null || destination == null)
            {
                return(null);
            }

            if (source.Cast <DictionaryEntry>().Where(de => destination.Contains(de.Key)).Any(de => destination[de.Key] != de.Value))
            {
                return(false);
            }

            return(destination.Cast <DictionaryEntry>().Where(de => source.Contains(de.Key)).All(de => source[de.Key] == de.Value));
        }
Ejemplo n.º 7
0
        internal void Load(IDictionary envVariables)
        {
            Data = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            var filteredEnvVariables = envVariables
                                       .Cast <DictionaryEntry>()
                                       .SelectMany(AzureEnvToAppEnv)
                                       .Where(entry => ((string)entry.Key).StartsWith(_prefix, StringComparison.OrdinalIgnoreCase));

            foreach (var envVariable in filteredEnvVariables)
            {
                var key = ((string)envVariable.Key).Substring(_prefix.Length);
                Data[key] = (string)envVariable.Value;
            }
        }
        internal void Load(IDictionary envVariables)
        {
            Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            var filteredEnvVariables = envVariables
                .Cast<DictionaryEntry>()
                .SelectMany(AzureEnvToAppEnv)
                .Where(entry => ((string)entry.Key).StartsWith(_prefix, StringComparison.OrdinalIgnoreCase));

            foreach (var envVariable in filteredEnvVariables)
            {
                var key = ((string)envVariable.Key).Substring(_prefix.Length);
                Data[key] = (string)envVariable.Value;
            }
        }
Ejemplo n.º 9
0
 public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
 {
     if (_dictionary != null)
     {
         return(_dictionary.Cast <DictionaryEntry>().Select(de => new KeyValuePair <TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator());
     }
     else if (_readOnlyDictionary != null)
     {
         return(_readOnlyDictionary.GetEnumerator());
     }
     else
     {
         return(_genericDictionary.GetEnumerator());
     }
 }
Ejemplo n.º 10
0
        // internal for tests
        internal void Load(IDictionary envVariables)
        {
            Data = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (var envVariable in envVariables.Cast <DictionaryEntry>())
            {
                var key = (string)envVariable.Key;

                if (!key.StartsWith("hazelcast.", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                key       = key.Replace(".", ConfigurationPath.KeyDelimiter, StringComparison.Ordinal);
                Data[key] = (string)envVariable.Value;
            }
        }
Ejemplo n.º 11
0
        public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
        {
            if (_dictionary != null)
            {
                return(_dictionary.Cast <DictionaryEntry>().Select(de => new KeyValuePair <TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator());
            }
#if HAVE_READ_ONLY_COLLECTIONS
            else if (_readOnlyDictionary != null)
            {
                return(_readOnlyDictionary.GetEnumerator());
            }
#endif
            else
            {
                return(GenericDictionary.GetEnumerator());
            }
        }
Ejemplo n.º 12
0
        static void InvalidateEnvironmentVariablesForUserCacheIfMachineEnvironmentVariablesHaveChanged()
        {
            var currentMachineEnvironmentVariables     = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine);
            var machineEnvironmentVariablesHaveChanged =
#pragma warning disable DE0006 // API is deprecated
                !currentMachineEnvironmentVariables.Cast <DictionaryEntry>()
                .OrderBy(e => e.Key)
                .SequenceEqual(mostRecentMachineEnvironmentVariables.Cast <DictionaryEntry>().OrderBy(e => e.Key));

#pragma warning restore DE0006 // API is deprecated

            if (machineEnvironmentVariablesHaveChanged)
            {
                mostRecentMachineEnvironmentVariables = currentMachineEnvironmentVariables;
                EnvironmentVariablesForUserCache.Clear();
            }
        }
Ejemplo n.º 13
0
        public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
        {
            if (_dictionary != null)
            {
                return(_dictionary.Cast <DictionaryEntry>().Select(de => new KeyValuePair <TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator());
            }
#if !(NET40 || NET35 || NET20 || PORTABLE40)
            else if (_readOnlyDictionary != null)
            {
                return(_readOnlyDictionary.GetEnumerator());
            }
#endif
            else
            {
                return(_genericDictionary.GetEnumerator());
            }
        }
Ejemplo n.º 14
0
        internal void DumpEnvironmentVariables(ILogger logger)
        {
            // Only dump env vars in debug mode.
            if (!_options.Verbose)
            {
                return;
            }

            logger.LogVerbose("Starting Environment Variable Values:");
            IDictionary envVars = Environment.GetEnvironmentVariables();

            foreach (DictionaryEntry item in envVars.Cast <DictionaryEntry>().OrderBy(de => de.Key))
            {
                logger.LogVerbose($"    {item.Key}: {item.Value}");
            }

            logger.LogVerbose(string.Empty);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 转换为<see cref="Dictionary{TKey, TValue}"/>
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dictionary"></param>
        /// <param name="keySetter">设置Key的委托</param>
        /// <param name="valueSetter">设置Value的委托</param>
        /// <param name="otherAction">在转换后需要执行的其它委托</param>
        /// <returns></returns>
        public static Dictionary <TKey, TValue> ToDictionary <TKey, TValue>(
            this IDictionary dictionary,
            Func <DictionaryEntry, TKey> keySetter,
            Func <DictionaryEntry, TValue> valueSetter,
            Func <IEnumerable <KeyValuePair <TKey, TValue> >, IEnumerable <KeyValuePair <TKey, TValue> > > otherAction = null)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException(nameof(dictionary));
            }

            IEnumerable <KeyValuePair <TKey, TValue> > temp = dictionary
                                                              .Cast <DictionaryEntry>()
                                                              .Select(t => KeyValuePair.Create(keySetter(t), valueSetter(t)));

            temp = otherAction == null ? temp : otherAction(temp);

            return(new Dictionary <TKey, TValue>(temp));
        }
Ejemplo n.º 16
0
        private static void MergeDictionaries(PropertyInfo property, object srcObj, object targetObj,
                                              ImageInfoMergeOptions options)
        {
            IDictionary srcDict = (IDictionary)property.GetValue(srcObj);

            if (srcDict == null)
            {
                return;
            }

            IDictionary targetDict = (IDictionary)property.GetValue(targetObj);

            if (srcDict.Cast <object>().Any())
            {
                if (targetDict != null)
                {
                    foreach (dynamic kvp in srcDict)
                    {
                        if (targetDict.Contains(kvp.Key))
                        {
                            object newValue = kvp.Value;
                            if (newValue is string)
                            {
                                targetDict[kvp.Key] = newValue;
                            }
                            else
                            {
                                MergeData(kvp.Value, targetDict[kvp.Key], options);
                            }
                        }
                        else
                        {
                            targetDict[kvp.Key] = kvp.Value;
                        }
                    }
                }
                else
                {
                    property.SetValue(targetObj, srcDict);
                }
            }
        }
        /// <summary>
        /// Expose the specified context attributes and/or the current
        /// IApplicationContext in the Quartz SchedulerContext.
        /// </summary>
        private void PopulateSchedulerContext()
        {
            // Put specified objects into Scheduler context.
            if (schedulerContextMap != null)
            {
                var dictionary = schedulerContextMap.Cast <DictionaryEntry>().ToDictionary(entry => entry.Key.ToString(), entry => entry.Value);
                scheduler.Context.PutAll(dictionary);
            }

            // Register IApplicationContext in Scheduler context.
            if (applicationContextSchedulerContextKey != null)
            {
                if (applicationContext == null)
                {
                    throw new SystemException("SchedulerFactoryObject needs to be set up in an IApplicationContext " +
                                              "to be able to handle an 'applicationContextSchedulerContextKey'");
                }
                scheduler.Context.Put(applicationContextSchedulerContextKey, applicationContext);
            }
        }
Ejemplo n.º 18
0
        private static void LogExceptionData(IDictionary data)
        {
            var dataEntries = data
                              .Cast <DictionaryEntry>()
                              .Select(x => new { Key = x.Key.ToString(), Value = x.Value?.ToString() ?? "" })
                              .OrderBy(x => x.Key)
                              .ToList();

            if (!dataEntries.Any())
            {
                return;
            }

            Log("   EXCEPTION DATA:");

            dataEntries.ForEach(x =>
            {
                Log($"      {x.Key}: {x.Value ?? ""}");
            });
        }
Ejemplo n.º 19
0
        private void AppendProcessVariables(ProcessStartInfo processInfo, IDictionary variables)
        {
            var environment = processInfo.Environment;

            foreach (var variable in variables.Cast <DictionaryEntry>())
            {
                var name  = variable.Key as string;
                var value = variable.Value as string;

                if (name == "Path")
                {
                    var path      = string.Join(";", environment.ContainsKey(name) ? environment[name] : string.Empty, value);
                    var pathParts = path.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Distinct();
                    processInfo.Environment[name] = string.Join(";", pathParts);
                }
                else
                {
                    processInfo.Environment[name] = value;
                }
            }
        }
Ejemplo n.º 20
0
        public static string ResponseToString(Method Method, string Url, Encoding Encoding, IDictionary <string, string> CookiesNameValues, IDictionary <string, string> ParamKeyValues)
        {
            using (var webClient = new WebClient())
            {
                var uri        = new Uri(Url);
                var webRequest = WebRequest.Create(uri);
                CookiesNameValues.Cast <KeyValuePair <string, string> >().ToList().ForEach(x => webRequest.TryAddCookie(new Cookie(x.Key, x.Value, "/", uri.Host)));
                webRequest.Method      = Method.ToString();
                webRequest.ContentType = "application/x-www-form-urlencoded";
                var parambytes = Encoding.ASCII.GetBytes(string.Join("&", ParamKeyValues.ToList().Select(x => x.Key + "=" + x.Value)));
                webRequest.ContentLength = parambytes.Length;
                using (var stream = webRequest.GetRequestStream())
                    stream.Write(parambytes, 0, parambytes.Length);

                var response      = webRequest.GetResponse();
                var receiveStream = response.GetResponseStream();
                var readStream    = new System.IO.StreamReader(receiveStream, Encoding);
                var htmlCode      = readStream.ReadToEnd();
                return(htmlCode);
            }
        }
Ejemplo n.º 21
0
        public AutomationAccount UpdateAutomationAccount(string resourceGroupName, string automationAccountName, string plan, IDictionary tags)
        {
            Requires.Argument("ResourceGroupName", resourceGroupName).NotNull();
            Requires.Argument("AutomationAccountName", automationAccountName).NotNull();

            var automationAccount = GetAutomationAccount(resourceGroupName, automationAccountName);

            IDictionary <string, string> accountTags = null;

            if (tags != null)
            {
                accountTags = tags.Cast <DictionaryEntry>()
                              .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
            }
            else
            {
                accountTags = automationAccount.Tags.Cast <DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());;
            }

            var accountUpdateParameters = new AutomationAccountPatchParameters()
            {
                Name       = automationAccountName,
                Properties = new AutomationAccountPatchProperties()
                {
                    Sku = new Sku()
                    {
                        Name = String.IsNullOrWhiteSpace(plan) ? automationAccount.Plan : plan,
                    }
                },
                Tags = accountTags,
            };

            var account =
                this.automationManagementClient.AutomationAccounts.Patch(resourceGroupName,
                                                                         accountUpdateParameters).AutomationAccount;


            return(new AutomationAccount(resourceGroupName, account));
        }
        private static void destructuringData(Exception exception, Dictionary <string, string> dataDictionary)
        {
            if (exception is null)
            {
                return;
            }

            IDictionary data = exception.Data;

            if (data != null && data.Count > 0)
            {
                Dictionary <string, string> dataDic = data
                                                      .Cast <DictionaryEntry>()
                                                      .Where(x => x.Key is string && x.Value != null)
                                                      .ToDictionary(x => x.Key as string, x => x.Value.ToString());

                foreach (var item in dataDic)
                {
                    dataDictionary.TryAdd(item.Key, item.Value);
                }
            }

            destructuringData(exception.InnerException, dataDictionary);
        }
Ejemplo n.º 23
0
        void HandleCreateOrUpdateRequest(IDictionary NewValues, object FromTimeOld, ParameterCollection DataSourceParams)
        {
            var slots = NewValues.Cast <DictionaryEntry>()
                        .Where(e => ((string)e.Key).EndsWith("Price"))
                        .Select(e => string.Format(@"
                                 <slot>
                                     <work_week_id>{0}</work_week_id>
                                     <theater_id>{1}</theater_id>
                                     <seat_type_id>{2}</seat_type_id>
                                     <from_time_new>{3}</from_time_new>
                                     <from_time_old>{4}</from_time_old>
                                     <week_day_code_val>{5}</week_day_code_val>
                                     <price>{6}</price>
                                 </slot>",
                                                   _workWeekID,
                                                   _theaterID,
                                                   _seatTypeID,
                                                   NewValues["StartTime"],
                                                   FromTimeOld,
                                                   Utilities.WeekDays.FromValue(((string)e.Key).Replace("Price", "")),
                                                   e.Value)).JoinStrings();

            DataSourceParams["Xml"].DefaultValue = string.Format(@"<data>{0}</data>", slots);
        }
Ejemplo n.º 24
0
        public void Write_Dictionary_CallsBufferWriter(IDictionary data)
        {
            var count = data.Cast <object>().Count();

            var buffer = new DummyBuffer();

            var contextMock = NewWriteContextMock();

            contextMock.SetupPath("Count", count);

            int i = 0;

            foreach (var key in data.Keys)
            {
                contextMock.SetupPath($"[{i}].Key", key);
                contextMock.SetupPath($"[{i}].Value", data[key]);

                i++;
            }

            Format.Write(data, contextMock.Object);

            contextMock.Verify();
        }
Ejemplo n.º 25
0
        private static string ObjectToString(Object obj)
        {
            if (obj != null)
            {
                //Check if the result is an IDictionary (e.g. Hashtable). In this case we will return the items within the dictionary
                if (obj is IDictionary)
                {
                    IDictionary idc = obj as IDictionary;

                    //See [IDictionary to string](http://stackoverflow.com/questions/12197089/idictionary-to-string) by [Daniel Hilgarth](http://blog.fire-development.com/)
                    string entries = idc.Cast <DictionaryEntry>()
                                     .Aggregate(new StringBuilder(),
                                                (sb, x) => sb.Append(" ").Append(x.Key.ToString()).Append(": ").Append(x.Value).Append(";"),
                                                sb => sb.ToString());

                    return("(" + obj.GetType().ToString() + ") =>" + entries);
                }
                else
                {
                    if (obj is string)
                    {
                        //If it's a string, display as is without type description
                        return(obj.ToString());
                    }
                    else
                    {
                        //"No idea how to display it better" format...
                        return(string.Format("{0} ({1})", obj.ToString(), obj.GetType().ToString()));
                    }
                }
            }
            else
            {
                return("NULL");
            }
        }
Ejemplo n.º 26
0
 IEnumerator <Item> IEnumerable <Item> .GetEnumerator()
 {
     return(equipped.Cast <Item>().GetEnumerator());
 }
Ejemplo n.º 27
0
        IDictionary<string, string> GetHeaders(IDictionary result)
        {
            if (result == null) return new Dictionary<string, string>();

            return result.Cast<DictionaryEntry>()
                .ToDictionary(e => (string)e.Key, e => Encoding.GetString((byte[])e.Value));
        }
 public static IDictionary <TKey, TValue> OfKeyValueType <TKey, TValue>(this IDictionary dictionary)
 {
     return(dictionary.Cast <DictionaryEntry>().Where(e => e.Key is TKey && e.Value is TValue).ToDictionary(e => (TKey)e.Key, e => (TValue)e.Value));
 }
 public static IDictionary <TKey, object> OfKeyType <TKey>(this IDictionary dictionary)
 {
     return(dictionary.Cast <DictionaryEntry>().Where(e => e.Key is TKey).ToDictionary(e => (TKey)e.Key, e => e.Value));
 }
Ejemplo n.º 30
0
        public AutomationAccount CreateAutomationAccount(string resourceGroupName, string automationAccountName,
            string location, string plan, IDictionary tags)
        {
            Requires.Argument("ResourceGroupName", resourceGroupName).NotNull();
            Requires.Argument("Location", location).NotNull();
            Requires.Argument("AutomationAccountName", automationAccountName).NotNull();

            IDictionary<string, string> accountTags = null;
            if (tags != null)
                accountTags = tags.Cast<DictionaryEntry>()
                    .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());

            var accountCreateOrUpdateParameters = new AutomationAccountCreateOrUpdateParameters()
            {
                Location = location,
                Name = automationAccountName,
                Properties = new AutomationAccountCreateOrUpdateProperties()
                {
                    Sku = new Sku()
                    {
                        Name = String.IsNullOrWhiteSpace(plan) ? Constants.DefaultPlan : plan,
                    }
                },
                Tags = accountTags
            };

            var account =
                this.automationManagementClient.AutomationAccounts.CreateOrUpdate(resourceGroupName,
                    accountCreateOrUpdateParameters).AutomationAccount;


            return new AutomationAccount(resourceGroupName, account);
        }
Ejemplo n.º 31
0
        public Module UpdateModule(string automationAccountName, IDictionary tags, string name, Uri contentLinkUri, string contentLinkVersion)
        {
            var moduleModel = this.automationManagementClient.Modules.Get(automationAccountName, name).Module;
            if(tags != null && contentLinkUri != null)
            {
                var moduleCreateParameters = new AutomationManagement.Models.ModuleCreateParameters();
                
                moduleCreateParameters.Name = name;
                moduleCreateParameters.Tags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());

                moduleCreateParameters.Properties = new ModuleCreateProperties();
                moduleCreateParameters.Properties.ContentLink = new AutomationManagement.Models.ContentLink();
                moduleCreateParameters.Properties.ContentLink.Uri = contentLinkUri;
                moduleCreateParameters.Properties.ContentLink.Version =
                    (String.IsNullOrWhiteSpace(contentLinkVersion))
                        ? Guid.NewGuid().ToString()
                        : contentLinkVersion;

                this.automationManagementClient.Modules.Create(automationAccountName,
                    moduleCreateParameters);

            }
            else if (contentLinkUri != null)
            {
                var moduleUpdateParameters = new AutomationManagement.Models.ModuleUpdateParameters();

                moduleUpdateParameters.Name = name;
                moduleUpdateParameters.Properties = new ModuleUpdateProperties();
                moduleUpdateParameters.Properties.ContentLink = new AutomationManagement.Models.ContentLink();
                moduleUpdateParameters.Properties.ContentLink.Uri = contentLinkUri;
                moduleUpdateParameters.Properties.ContentLink.Version =
                    (String.IsNullOrWhiteSpace(contentLinkVersion))
                        ? Guid.NewGuid().ToString()
                        : contentLinkVersion;

                moduleUpdateParameters.Tags = moduleModel.Tags;

                this.automationManagementClient.Modules.Update(automationAccountName, moduleUpdateParameters);
            }
            else if(tags != null)
            {
                var moduleUpdateParameters = new AutomationManagement.Models.ModuleUpdateParameters();
                
                moduleUpdateParameters.Name = name;
                moduleUpdateParameters.Tags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
                moduleUpdateParameters.Properties = new ModuleUpdateProperties();

                this.automationManagementClient.Modules.Update(automationAccountName, moduleUpdateParameters);
            }

            var updatedModule = this.automationManagementClient.Modules.Get(automationAccountName, name).Module;
            return new Module(automationAccountName, updatedModule);
        }
Ejemplo n.º 32
0
        public Runbook CreateRunbookByName(string resourceGroupName, string automationAccountName, string runbookName, string description,
            IDictionary tags, string type, bool? logProgress, bool? logVerbose, bool overwrite)
        {
            using (var request = new RequestSettings(this.automationManagementClient))
            {
                var runbookModel = this.TryGetRunbookModel(resourceGroupName, automationAccountName, runbookName);
                if (runbookModel != null && overwrite == false)
                {
                    throw new ResourceCommonException(typeof (Runbook),
                        string.Format(CultureInfo.CurrentCulture, Resources.RunbookAlreadyExists, runbookName));
                }

                IDictionary<string, string> runbooksTags = null;
                if (tags != null) runbooksTags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());

                var rdcprop = new RunbookCreateOrUpdateDraftProperties()
                {
                    Description = description,
                    RunbookType = String.IsNullOrWhiteSpace(type) ? RunbookTypeEnum.Script : (0 == string.Compare(type, Constants.RunbookType.PowerShellWorkflow, StringComparison.OrdinalIgnoreCase)) ? RunbookTypeEnum.Script : type,
                    LogProgress =  logProgress.HasValue && logProgress.Value,
                    LogVerbose = logVerbose.HasValue && logVerbose.Value,
                    Draft = new RunbookDraft(),
                };

                var rdcparam = new RunbookCreateOrUpdateDraftParameters()
                {
                    Name = runbookName,
                    Properties = rdcprop,
                    Tags = runbooksTags,
                    Location = GetAutomationAccount(resourceGroupName, automationAccountName).Location
                };

                this.automationManagementClient.Runbooks.CreateOrUpdateWithDraft(resourceGroupName, automationAccountName, rdcparam);

                return this.GetRunbook(resourceGroupName, automationAccountName, runbookName);
            }
        }
Ejemplo n.º 33
0
        /* ParameterInputPrompt: edit parametrs to start and run the application in `MainForm`
         * This is called after `ConfigurationOptionPrompt` to modify parameters in `AppInpPrm.OptionSections`
         * + LAYOUT:
         *      - Initialize general variables related to dialog's component's size, position and font
         *      - Initialize the dialog and its title + tab components:
         *              * Each tab represents a section in `AppInpPrm.OptionSections`
         *              * Within each tab are the parameters in the corresponding section to edit
         *      - Initialize TabPage for each section
         *      - For each element in each section, add a label and proccess the element according to the type:
         *              * Textbox: just add the TextBox
         *              * RadiobuttonGroup:
         *                  (a) Obtain the corresponding option dictionary
         *                  (b) Add a panel to group the radio buttons
         *                  (c) For each option, add a `RadioButton` button object showing the description
         *                  (d) Check the button representing the value loaded from the configuration file
         *              * ColorButton: create a `Button` that can prompt a `ColorDialog`
         *      - Add a button to prompt a folder dialog for choosing the output file directory
         *      - Process the changes made after the prompt is closed (to continue) and save configuration set up to a file
         * + INPUT:
         *      - title:                    the tile of the dialog
         *      - caption:                  the caption of the dialog
         * + OUTPUT:
         *      - a modified `AppInpPrm`
         *
         */
        private ApplicationInputParameters ParameterInputPrompt(string title, string caption)
        {
            // (1) Initialize general variables related to dialog's component's size, position and font
            // General dialog variables
            Size  prompt_size = new Size(1000, 700);
            Point title_coord = new Point(50, 20);
            Size  title_size  = new Size(600, 50);
            // General tab variables
            Point tabcntl_coord = new Point(50, 80);
            Size  tabcntl_size  = new Size(900, 500);
            Point tabpage_coord = new Point(50, 20);
            Size  tabpage_size  = new Size(800, 500);

            // Variables for subcomponents in the tab
            const int max_radio_col = 4;
            const int top_label_begin = 30, left_label = 10, width_label = 300;
            const int top_box_begin = top_label_begin, left_box = 320, width_box = 500;
            const int width_clrbt = width_box / 3;
            const int general_spacing = 32;
            const int top_offset_radiogroup = 10, top_offset_radiobutton = 5, left_offset_radiobutton = 20, width_radio = 120;
            const int radio_spacing = 25;

            // Folder dialog
            const int horz_offset_folderdialog = 200, vert_offset_folderdialog = 10;

            // Confirmation and Exit buttons
            Size      end_button_size        = new Size(120, 30);
            const int top_offset_endbutton   = 20;
            const int horz_spacing_endbutton = 10;

            // Fonts
            Font lbl_font = new Font(fontname, 10F, FontStyle.Bold, GraphicsUnit.Point);
            Font box_font = new Font(fontname, 10F, FontStyle.Regular, GraphicsUnit.Point);
            Font rdb_font = new Font(fontname, 8F, FontStyle.Regular, GraphicsUnit.Point);
            Font tab_font = new Font(fontname, 11F, FontStyle.Regular, GraphicsUnit.Point);
            Font ttl_font = new Font(fontname, 20F, FontStyle.Bold, GraphicsUnit.Point);

            // radio_choice_dictionaries:   nested dictionary to save the the dictionary objects (representing the option dictionary in `ApplicationInputParameters`
            //                              the first key refers to the name of the parameter of interest (only parameters with `ApplicationInputParameters.PropertypAndFormType.FormType` = `RadiobuttonGroup`)
            //                              the second key refers to the alias/description (`prop_alias` in `ApplicationInputParameters.PropertypAndFormType`), which would appear on the text of each RadioButton
            //                              the final value refers to the actual value to be assigned to the parameter.
            // for example, if the parameter is `window_type` then:
            //      >> radio_choice_dictionaries["window_type"] = AppInpPrm.wintype_dict
            Dictionary <string, Dictionary <string, object> > radio_choice_dictionaries = new Dictionary <string, Dictionary <string, object> >();

            // Number of sections like "Input and Output", "General plot options", ...
            int number_tabs = AppInpPrm.OptionSections.Count;

            // (2) Initialize the dialog and its title + tab components
            MainPrompt = new Form()
            {
                Size            = prompt_size,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                Text            = caption,
                StartPosition   = FormStartPosition.CenterParent,
                TopMost         = true
            };
            Label PromptTitle = new Label()
            {
                Location  = title_coord,
                Size      = title_size,
                Text      = title,
                TextAlign = ContentAlignment.MiddleLeft,
                Font      = ttl_font
            };

            MainPrompt.Controls.Add(PromptTitle);
            TabControl TabCntl = new TabControl()
            {
                Location = tabcntl_coord,
                Size     = tabcntl_size,
                Font     = tab_font,
                // Appearance = TabAppearance.FlatButtons
            };

            TabPage[] TabPages = new TabPage[number_tabs];

            // Control list (dictionary) to add the components corresponding to each parameter
            Dictionary <string, Control> Cntl_List = new Dictionary <string, Control>();

            // RadioButton list to contain all the RadioButton objectes
            List <RadioButton> Radio_List = new List <RadioButton>();

            // For each section
            for (int i = 0; i < number_tabs; i++)
            {
                string section_name = AppInpPrm.OptionSections.Keys.ElementAt(i);
                Dictionary <string, ApplicationInputParameters.PropertypAndFormType> section_options = AppInpPrm.OptionSections[section_name];

                // (3) Initialize TabPage for each section
                TabPages[i] = new TabPage()
                {
                    Location = tabpage_coord,
                    Size     = tabpage_size,
                    Text     = section_name
                };

                int    number_elements = section_options.Count;
                int    top_label = top_box_begin;
                int    top_box = top_label_begin;
                string prop_alias, prop_name;

                // (4) For each element in each section
                for (int j = 0; j < number_elements; j++)
                {
                    prop_name  = section_options.Keys.ElementAt(j);         // like "hostname"
                    prop_alias = section_options[prop_name].prop_alias;     // like "Host name"
                    var prop_val = AppInpPrm.GetPropValue(prop_name);       // the value from the loaded config file

                    // Add a desciptor label for each parameter
                    Cntl_List.Add("label_of_" + prop_name, new Label()
                    {
                        Location  = new Point(left_label, top_label),
                        Text      = prop_alias,
                        Width     = width_label,
                        TextAlign = ContentAlignment.MiddleRight,
                        Font      = lbl_font
                    });
                    TabPages[i].Controls.Add(Cntl_List["label_of_" + prop_name]);
                    top_label += general_spacing;

                    // Process the element according to the type (`ApplicationInputParameters.PropertypAndFormType.FormType`)
                    if (section_options[prop_name].IsTextBox())
                    {
                        // Simplest case: Textbox, just add a `TextBox` object
                        // the value to be changed would be whatever the text in `TextBox.Text`
                        Cntl_List.Add(prop_name, new TextBox()
                        {
                            Location    = new Point(left_box, top_box),
                            Width       = width_box,
                            Text        = prop_val.ToString(),
                            Font        = box_font,
                            BorderStyle = BorderStyle.FixedSingle
                        });
                    }
                    else if (section_options[prop_name].IsRadiobuttonGroup())
                    {
                        // RadiobuttonGroup:
                        // (a) Obtain the corresponding option dictionary
                        // (b) Add a panel to group the radio buttons
                        // (c) For each option, add a `RadioButton` button object showing the description
                        // (d)Check the button representing the value loaded from the configuration file

                        // (a) Casting a dicionary object to add to `radio_choice_dictionaries`; source:
                        // https://stackoverflow.com/questions/10206557/c-sharp-cast-dictionarystring-anytype-to-dictionarystring-object-involvin
                        string      dict_name            = section_options[prop_name].dict_name;
                        IDictionary _dict_               = (IDictionary)AppInpPrm.GetPropValue(dict_name);
                        Dictionary <string, object> dict = _dict_.Cast <dynamic>().ToDictionary(entry => (string)entry.Key, entry => entry.Value);
                        radio_choice_dictionaries.Add(prop_name, dict);

                        // (b) Add a `Panel` object to group the `RadioButton` objects
                        // because each group of `RadioButton` objects can only have 1 checked button
                        int radio_group_height = (int)Math.Ceiling(((double)dict.Count) / ((double)max_radio_col)) * radio_spacing + top_offset_radiogroup;
                        Cntl_List.Add(prop_name, new Panel()
                        {
                            Location    = new Point(left_box, top_box - top_offset_radiogroup),
                            Size        = new Size(width_box, radio_group_height),
                            BorderStyle = BorderStyle.None
                        });
                        top_box   += radio_group_height - top_offset_radiogroup - radio_spacing;
                        top_label += radio_group_height - top_offset_radiogroup - radio_spacing;

                        int default_idx = -1; // the index of the one that records the initial value loaded from the configuration file
                        int cur_radio_row = 0, cur_radio_col = 0;
                        for (int i_rdbtr = 0; i_rdbtr < dict.Count; i_rdbtr++)
                        {
                            // (c) For each option, add a `RadioButton` button object showing the description
                            cur_radio_row = (int)Math.Floor(((double)i_rdbtr) / ((double)max_radio_col));
                            cur_radio_col = i_rdbtr % max_radio_col;
                            var i_key = dict.Keys.ElementAt(i_rdbtr).ToString();
                            Radio_List.Add(new RadioButton()
                            {
                                Location = new Point(left_offset_radiobutton + width_radio * cur_radio_col, top_offset_radiobutton + radio_spacing * cur_radio_row),
                                Size     = new Size(width_radio, radio_spacing),
                                Font     = rdb_font,
                                Text     = i_key
                            });
                            Cntl_List[prop_name].Controls.Add(Radio_List[Radio_List.Count - 1]);

                            if (string.Compare(prop_val.ToString(), dict[i_key].ToString()) == 0)
                            {
                                default_idx = Radio_List.Count - 1;
                            }
                        }
                        // (d) Check the button representing the value loaded from the configuration file
                        Radio_List[default_idx].Checked = true;
                    }
                    else if (section_options[prop_name].IsColorButton())
                    {
                        // ColorButton: create a `Button` that can prompt a `ColorDialog`
                        // the initial color would be the same as the color loaded from the
                        // configuration file
                        Cntl_List.Add(prop_name, new Button()
                        {
                            Location  = new Point(left_box, top_box),
                            Width     = width_clrbt,
                            Font      = box_font,
                            BackColor = (Color)prop_val,
                            FlatStyle = FlatStyle.Flat,
                        });
                        // Add tooltip
                        (new ToolTip()).SetToolTip(Cntl_List[prop_name], "Click to select " + prop_alias);
                        ((Button)Cntl_List[prop_name]).FlatAppearance.BorderSize = 0;
                        Cntl_List[prop_name].Click += (sender, e) =>
                        {
                            // Prompt the color dialog to select a color
                            // sadly this does not include the transparency factor
                            // it'd be nice to be able to include that though
                            ColorDialog colorDialog = new ColorDialog()
                            {
                                AllowFullOpen = true,
                                ShowHelp      = false,
                                Color         = (sender as Button).BackColor
                            };
                            // Then change the color of the button after choice of color is finalized in the color dialog
                            if (colorDialog.ShowDialog() == DialogResult.OK)
                            {
                                (sender as Button).BackColor = colorDialog.Color;
                            }
                        };
                    }
                    TabPages[i].Controls.Add(Cntl_List[prop_name]);
                    top_box += general_spacing;
                }
                // Add the `TabPage` to `TabControl`
                TabCntl.Controls.Add(TabPages[i]);
            }

            // Add the `TabControl` to the main dialog `MainPrompt`
            MainPrompt.Controls.Add(TabCntl);

            // (4) Add a button to prompt a folder dialog for choosing the output file directory
            Button FolderDialogButton = new Button()
            {
                Text      = "Choose folder and file name",
                Location  = new Point(left_box + horz_offset_folderdialog, Cntl_List["output_file_name"].Top + general_spacing),
                Size      = new Size(width_box - horz_offset_folderdialog, Cntl_List["output_file_name"].Height + vert_offset_folderdialog),
                Font      = box_font,
                BackColor = Color.WhiteSmoke,
                FlatStyle = FlatStyle.Flat
            };

            FolderDialogButton.FlatAppearance.MouseOverBackColor = Color.Silver;
            FolderDialogButton.Click += (sender, e) => {
                // https://stackoverflow.com/questions/11624298/how-to-use-openfiledialog-to-select-a-folder by Daniel Ballinger
                OpenFileDialog folderBrowser = new OpenFileDialog()
                {
                    ValidateNames    = false,
                    CheckFileExists  = false,
                    CheckPathExists  = true,
                    InitialDirectory = AppInpPrm.output_folder
                };
                folderBrowser.FileName = "Choose folder then enter desired file name here";
                if (folderBrowser.ShowDialog() == DialogResult.OK)
                {
                    string fileName   = Path.GetFileName(folderBrowser.FileName);
                    string folderPath = Path.GetDirectoryName(folderBrowser.FileName);
                    Cntl_List["output_folder"].Text    = folderPath;
                    Cntl_List["output_file_name"].Text = fileName;
                }
            };
            TabPages[0].Controls.Add(FolderDialogButton);

            // (5) Add confirmation and exit button
            Button ConfirmationButton = new Button()
            {
                Text     = "Continue",
                Location = new Point(TabCntl.Left + TabCntl.Width - end_button_size.Width * 2 - horz_spacing_endbutton,
                                     TabCntl.Top + TabCntl.Height + top_offset_endbutton),
                Size         = end_button_size,
                DialogResult = DialogResult.OK,
                Font         = lbl_font,
                BackColor    = Color.WhiteSmoke,
                FlatStyle    = FlatStyle.Flat
            };

            ConfirmationButton.FlatAppearance.MouseOverBackColor = Color.Silver;
            ConfirmationButton.Click += (sender, e) => {
                MainPrompt.Close();
            };
            MainPrompt.Controls.Add(ConfirmationButton);
            MainPrompt.AcceptButton = ConfirmationButton;

            Button ExitButton = new Button()
            {
                Text     = "Exit",
                Location = new Point(ConfirmationButton.Left + ConfirmationButton.Width + horz_spacing_endbutton,
                                     TabCntl.Top + TabCntl.Height + top_offset_endbutton),
                Size      = end_button_size,
                Font      = lbl_font,
                BackColor = Color.WhiteSmoke,
                FlatStyle = FlatStyle.Flat
            };

            ExitButton.FlatAppearance.MouseOverBackColor = Color.Silver;
            ExitButton.Click += (sender, e) =>
            {
                MainPrompt.Close();
                Environment.Exit(1);
            };
            MainPrompt.Controls.Add(ExitButton);
            MainPrompt.CancelButton = ExitButton;

            // (6) Process the changes made after the prompt is closed (to continue) and save configuration set up to a file
            if (MainPrompt.ShowDialog() == DialogResult.OK)
            {
                // Description dictionary for addional descripton of values
                // (also refer to the discussion of configuration file template in the "ApplicationInputParameters.cs"
                // Key: the name of the parameter
                // Value:
                //      + [default] <NAN>: meaning there's no additional description here
                //      + if the parameter's value is from an option dictionary, this is one of the
                //          KEYS (descriptor) in the dictionary (not the VALUES)
                //      + if this is a color, the method is `Color.ToString()` to get either
                //          the name of the color, or an ARGB array of it
                Dictionary <string, string> description_dict = new Dictionary <string, string>();
                foreach (var item in Cntl_List)
                {
                    string  prop_name = item.Key;
                    Control cntl_obj  = item.Value;
                    if (cntl_obj is TextBox)
                    {
                        // set new value by `TextBox.Text`
                        // the parsing is done by reflection in `ApplicationInputParameters`
                        AppInpPrm.SetPropValue(prop_name, cntl_obj.Text);
                        description_dict[prop_name] = "<NAN>";
                    }
                    else if (cntl_obj is Panel)
                    {
                        // obtain the checked button and the corresponding option/choice dictionary
                        // in order to set the parameter's value properly
                        Dictionary <string, object> prop_dict = radio_choice_dictionaries[prop_name];
                        var checkedButton = cntl_obj.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked);

                        AppInpPrm.SetPropValue(prop_name, prop_dict[checkedButton.Text]);
                        description_dict[prop_name] = checkedButton.Text;
                    }
                    else if (cntl_obj is Button)
                    {
                        // set new color value
                        AppInpPrm.SetPropValue(prop_name, cntl_obj.BackColor);
                        description_dict[prop_name] = AppInpPrm.GetPropValue(prop_name).ToString();
                    }
                    else // some of these are just labels, hence ignore
                    {
                        continue;
                    }
                }
                AppInpPrm.CompleteInitialize(); // for all the necessary checking and parsing of parameters

                // saving the configuration changes to a file
                string config_file = Cntl_List["config_path"].Text;
                AppInpPrm.WriteConfigurationFile(config_file, description_dict);
            }
            // The modified `AppInpPrm` is returned then assigned to `Result` of `Prompt`
            return(AppInpPrm);
        }
Ejemplo n.º 34
0
 public static Dictionary <TKey, TValue> ToDictionary <TKey, TValue>(
     this IDictionary dictionary,
     IEqualityComparer <TKey> comparer) =>
 dictionary
 .Cast <DictionaryEntry>()
 .ToDictionary(entry => (TKey)entry.Key, entry => (TValue)entry.Value, comparer);
Ejemplo n.º 35
0
        public Model.DscConfiguration CreateConfiguration(
            string resourceGroupName,
            string automationAccountName,
            string sourcePath,
            IDictionary tags, 
            string description,
            bool? logVerbose,
            bool published,
            bool overWrite)
        {
            using (var request = new RequestSettings(this.automationManagementClient))
            {
                Requires.Argument("ResourceGroupName", resourceGroupName).NotNull();
                Requires.Argument("AutomationAccountName", automationAccountName).NotNull();
                Requires.Argument("SourcePath", sourcePath).NotNull();

                string fileContent = null;
                string configurationName = String.Empty;

                try
                {
                    if (File.Exists(Path.GetFullPath(sourcePath)))
                    {
                        fileContent = System.IO.File.ReadAllText(sourcePath);
                    }
                }
                catch (Exception)
                {
                    // exception in accessing the file path
                    throw new FileNotFoundException(
                                        string.Format(
                                            CultureInfo.CurrentCulture,
                                            Resources.ConfigurationSourcePathInvalid));
                }

                // configuration name is same as filename
                configurationName = Path.GetFileNameWithoutExtension(sourcePath);

                // for the private preview, configuration can be imported in Published mode only
                // Draft mode is not implemented
                if (!published)
                {
                    throw new NotImplementedException(
                                        string.Format(
                                            CultureInfo.CurrentCulture,
                                            Resources.ConfigurationNotPublished));
                }

                // if configuration already exists, ensure overwrite flag is specified
                var configurationModel = this.TryGetConfigurationModel(
                    resourceGroupName,
                    automationAccountName,
                    configurationName);
                if (configurationModel != null)
                {
                    if (!overWrite)
                    {
                        throw new ResourceCommonException(typeof(Model.DscConfiguration),
                            string.Format(CultureInfo.CurrentCulture, Resources.ConfigurationAlreadyExists, configurationName));
                    }
                }

                // location of the configuration is set to same as that of automation account
                string location = this.GetAutomationAccount(resourceGroupName, automationAccountName).Location;

                IDictionary<string, string> configurationTags = null;
                if (tags != null) configurationTags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());

                var configurationCreateParameters = new DscConfigurationCreateOrUpdateParameters()
                                                        {
                                                            Name = configurationName,
                                                            Location = location,
                                                            Tags = configurationTags,
                                                            Properties = new DscConfigurationCreateOrUpdateProperties()
                                                                    {
                                                                        Description = String.IsNullOrEmpty(description) ? String.Empty : description,
                                                                        LogVerbose = (logVerbose.HasValue) ? logVerbose.Value : false,
                                                                        Source = new Microsoft.Azure.Management.Automation.Models.ContentSource()
                                                                                {
                                                                                    // only embeddedContent supported for now
                                                                                    ContentType = Model.ContentSourceType.embeddedContent.ToString(),
                                                                                    Value = fileContent
                                                                                }
                                                                    }
                                                        };

                var configuration =
                    this.automationManagementClient.Configurations.CreateOrUpdate(
                        resourceGroupName,
                        automationAccountName,
                        configurationCreateParameters).Configuration;

                return new Model.DscConfiguration(resourceGroupName, automationAccountName, configuration);
            }
        }
 private Dictionary <string, object> parseExceptionData(IDictionary data)
 {
     return(data
            .Cast <DictionaryEntry>()
            .ToDictionary(de => de.Key as string, de => de.Value as object));
 }
Ejemplo n.º 37
0
        public Runbook UpdateRunbook(string resourceGroupName, string automationAccountName, string runbookName, string description,
            IDictionary tags, bool? logProgress, bool? logVerbose)
        {
            using (var request = new RequestSettings(this.automationManagementClient))
            {
                var runbookModel = this.TryGetRunbookModel(resourceGroupName, automationAccountName, runbookName);
                if (runbookModel == null)
                {
                    throw new ResourceCommonException(typeof (Runbook),
                        string.Format(CultureInfo.CurrentCulture, Resources.RunbookNotFound, runbookName));
                }

                var runbookUpdateParameters = new RunbookPatchParameters();
                runbookUpdateParameters.Name = runbookName;
                runbookUpdateParameters.Tags = null;

                IDictionary<string, string> runbooksTags = null;
                if (tags != null) runbooksTags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());

                runbookUpdateParameters.Properties = new RunbookPatchProperties();
                runbookUpdateParameters.Properties.Description = description ?? runbookModel.Properties.Description;
                runbookUpdateParameters.Properties.LogProgress = (logProgress.HasValue)
                    ? logProgress.Value
                    : runbookModel.Properties.LogProgress;
                runbookUpdateParameters.Properties.LogVerbose = (logVerbose.HasValue)
                    ? logVerbose.Value
                    : runbookModel.Properties.LogVerbose;
                runbookUpdateParameters.Tags = runbooksTags ?? runbookModel.Tags;

                var runbook =
                    this.automationManagementClient.Runbooks.Patch(resourceGroupName, automationAccountName, runbookUpdateParameters)
                        .Runbook;

                return new Runbook(resourceGroupName, automationAccountName, runbook);
            }
        }
Ejemplo n.º 38
0
        public Connection CreateConnection(string automationAccountName, string name, string connectionTypeName, IDictionary connectionFieldValues,
            string description)
        {
            var connectionModel = this.TryGetConnectionModel(automationAccountName, name);
            if (connectionModel != null)
            {
                throw new ResourceCommonException(typeof(Connection),
                    string.Format(CultureInfo.CurrentCulture, Resources.ConnectionAlreadyExists, name));
            }

            var ccprop = new ConnectionCreateProperties()
            {
                Description = description,
                ConnectionType = new ConnectionTypeAssociationProperty() { Name = connectionTypeName },
                FieldDefinitionValues = connectionFieldValues.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString())
            };

            var ccparam = new ConnectionCreateParameters() { Name = name, Properties = ccprop };

            var connection = this.automationManagementClient.Connections.Create(automationAccountName, ccparam).Connection;

            return new Connection(automationAccountName, connection);
        }
Ejemplo n.º 39
0
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            AssemblyNameOrPath = assemblyPath;

            var newSettings = settings as IDictionary<string, object>;
            Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);

            if (Settings.ContainsKey(PackageSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[PackageSettings.InternalTraceLevel], true);

                if (Settings.ContainsKey(PackageSettings.InternalTraceWriter))
                    InternalTrace.Initialize((TextWriter)Settings[PackageSettings.InternalTraceWriter], traceLevel);
#if !PORTABLE && !SILVERLIGHT
                else
                {
                    var workDirectory = Settings.ContainsKey(PackageSettings.WorkDirectory) ? (string)Settings[PackageSettings.WorkDirectory] : Env.DefaultWorkDirectory;
                    var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
#endif
            }
        }
Ejemplo n.º 40
0
        public Module CreateModule(string automationAccountName, Uri contentLink, string moduleName,
            IDictionary tags)
        {
            IDictionary<string, string> moduleTags = null;
            if (tags != null) moduleTags = tags.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
            var createdModule = this.automationManagementClient.Modules.Create(automationAccountName,
                new AutomationManagement.Models.ModuleCreateParameters()
                {
                    Name = moduleName,
                    Tags = moduleTags,
                    Properties = new AutomationManagement.Models.ModuleCreateProperties()
                    {
                        ContentLink = new AutomationManagement.Models.ContentLink()
                        {
                            Uri = contentLink,
                            ContentHash = null,
                            Version = null
                        }
                    },
                });

            return this.GetModule(automationAccountName, moduleName);
        }
Ejemplo n.º 41
0
        public AutomationAccount UpdateAutomationAccount(string resourceGroupName, string automationAccountName,
            string plan, IDictionary tags)
        {
            Requires.Argument("ResourceGroupName", resourceGroupName).NotNull();
            Requires.Argument("AutomationAccountName", automationAccountName).NotNull();

            var automationAccount = GetAutomationAccount(resourceGroupName, automationAccountName);

            IDictionary<string, string> accountTags = null;
            if (tags != null)
            {
                accountTags = tags.Cast<DictionaryEntry>()
                    .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
            }
            else
            {
                accountTags = automationAccount.Tags.Cast<DictionaryEntry>()
                    .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
                ;
            }

            var accountUpdateParameters = new AutomationAccountPatchParameters()
            {
                Name = automationAccountName,
                Properties = new AutomationAccountPatchProperties()
                {
                    Sku = new Sku()
                    {
                        Name = String.IsNullOrWhiteSpace(plan) ? automationAccount.Plan : plan,
                    }
                },
                Tags = accountTags,
            };

            var account =
                this.automationManagementClient.AutomationAccounts.Patch(resourceGroupName,
                    accountUpdateParameters).AutomationAccount;


            return new AutomationAccount(resourceGroupName, account);
        }
 public MapType(IDictionary value)
 {
     Entry = value.Cast<DictionaryEntry>()
       .Select(entry => new MapTypeEntry
                            {
                                Key = new GenericValueType(entry.Key),
                                Value = new GenericValueType(entry.Value)
                            })
       .ToArray();
 }
 private void AssertStateItems(IDictionary expected, ISessionStateItemCollection actual)
 {
     Assert.Equal(expected.Count, actual.Count);
     foreach (var kvp in expected.Cast<DictionaryEntry>())
     {
         var name = (string)kvp.Key;
         Assert.Equal(kvp.Value, actual[name]);
     }
 }
Ejemplo n.º 44
0
        public IDictionary <TKey, GeoCoordinate> Decode(IDictionary <TKey, GeoCoordinate> geoHashes)
        {
            var kvp = geoHashes.Cast <KeyValuePair <TKey, string> >();

            return(Decode(kvp).ToDictionary(x => x.Key, x => x.Value));
        }
Ejemplo n.º 45
0
        private void Initialize(string assemblyPath, IDictionary settings)
        {
            AssemblyNameOrPath = assemblyPath;

            var newSettings = settings as IDictionary<string, object>;
            Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);

            if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel))
            {
                var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true);

                if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter))
                    InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel);
#if !PORTABLE
                else
                {
                    var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory)
                        ? (string)Settings[FrameworkPackageSettings.WorkDirectory]
                        : Directory.GetCurrentDirectory();
#if NETSTANDARD1_6
                    var id = DateTime.Now.ToString("o");
#else      
                    var id = Process.GetCurrentProcess().Id;
#endif
                    var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyPath));
                    InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
                }
#endif
            }
        }