コード例 #1
0
        public List <KeyValuePair <string, int> > getChar(char c)
        {
            List <KeyValuePair <string, int> > result;
            string temp;

            if (c == '#')
            {
                temp     = tempChar.ToString();
                tempChar = new StringBuilder();
                if (mList.ContainsKey(temp))
                {
                    mList[temp] += 1;
                }
                else
                {
                    mList.Add(temp, 1);
                }
            }
            else
            {
                tempChar.Append(c);
                temp = tempChar.ToString();
            }
            result = mList.Cast <KeyValuePair <string, int> >()
                     .Where(kvp => kvp.Key.ToString().StartsWith(temp))
                     .ToList();

            var r = from kp in result
                    orderby kp.Value descending
                    orderby kp.Value
                    select kp;

            return(r.ToList());
        }
コード例 #2
0
        public TimeboxEnforcer()
        {
            _timer.Interval = 500;
            _timer.Tick    += TimerTick;
            IocContainer.Instance.Compose(this);
            InitializeComponent();

            UpdateDurationText();

            UpdateTimer(false);

            bool isConnected = SirenOfShameDevice.IsConnected;

            InitializeCombobox(_timeboxAudio, SirenOfShameDevice.AudioPatterns);
            InitializeCombobox(_timeboxLights, SirenOfShameDevice.LedPatterns);
            InitializeCombobox(_warningAudio, SirenOfShameDevice.AudioPatterns);
            InitializeCombobox(_warningLights, SirenOfShameDevice.LedPatterns);
            _warningDuration.Items.AddRange(_warningDurations.Cast <object>().ToArray());
            _warningDuration.SelectedIndex = 2;

            _warningLights.Enabled        = isConnected;
            _warningAudio.Enabled         = isConnected;
            _warningAudioDuration.Enabled = isConnected;
            _warningLightDuration.Enabled = isConnected;
            _timeboxLights.Enabled        = isConnected;
            _timeboxLightDuration.Enabled = isConnected;
            _timeboxAudio.Enabled         = isConnected;
            _timeboxAudioDuration.Enabled = isConnected;
        }
コード例 #3
0
 public List <AbuseReport> GetAbuseReports(int start, int count, string filter)
 {
     try
     {
         Dictionary <string, object> send = new Dictionary <string, object>
         {
             { "start", start },
             { "count", count },
             { "filter", filter },
             { "METHOD", "GetAbuseReports" }
         };
         List <string> m_ServerURIs =
             m_registry.RequestModuleInterface <IConfigurationService>().FindValueOf("AbuseReportsServerURI");
         Dictionary <string, object> ars =
             WebUtils.ParseXmlResponse(SynchronousRestFormsRequester.MakeRequest("POST",
                                                                                 m_ServerURIs[0],
                                                                                 WebUtils.BuildQueryString(send)));
         return(ars.Cast <AbuseReport>().ToList());
     }
     catch (Exception e)
     {
         MainConsole.Instance.DebugFormat("[ABUSEREPORT CONNECTOR]: Exception when contacting friends server: {0}", e.Message);
         return(null);
     }
 }
コード例 #4
0
ファイル: Docker.cs プロジェクト: sandboxa13/lacmus-app
        public async Task Initialize(string imageName = "gosha20777/test", string tag = "1")
        {
            tag = IS_GPU ? $"gpu-{API_VER}.{tag}" : $"{API_VER}.{tag}";
            try
            {
                var progressDictionary = new Dictionary <string, string>();
                var images             = await _client.Images.ListImagesAsync(new ImagesListParameters { MatchName = $"{imageName}:{tag}" });

                if (images.Count > 0)
                {
                    Console.WriteLine($"such image already exists: {images.First().ID}");
                    return;
                }

                var progress = new Progress <JSONMessage>();
                progress.ProgressChanged += (sender, message) =>
                {
                    try
                    {
                        if (progressDictionary.ContainsKey(message.ID) && message.Status.Contains("Pull complete",
                                                                                                  StringComparison.InvariantCultureIgnoreCase))
                        {
                            progressDictionary[message.ID] = message.Status;
                            var count = progressDictionary.Cast <string>().Count(value =>
                                                                                 value.Contains("Pull complete", StringComparison.InvariantCultureIgnoreCase));
                            Debug.Assert(progressDictionary.Count > 1, "progressDictionary.Count > 1");
                            Console.WriteLine($"{count}/{progressDictionary.Count - 1}");
                        }
                        else
                        {
                            progressDictionary.Add(message.ID, message.Status);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                };


                await _client.Images.CreateImageAsync(
                    new ImagesCreateParameters
                {
                    FromImage = $"{imageName}:{tag}"
                },
                    new AuthConfig
                {
                    Email    = "*****@*****.**",
                    Username = "******",
                    Password = "******"
                },
                    progress
                    );
            }
            catch (Exception e)
            {
                throw new Exception($"Unable to create docker image: {e.Message}");
            }
        }
コード例 #5
0
        private void LoadExamples()
        {
            this.lstExamples.DisplayMember = "Key";
            //this.lstExamples.ValueMember = "Value";
            var examples = new Dictionary <string, string> {
                { "Basics of SmartFormat",
                  @"Basics of SmartFormat
Similar to String.Format, SmartFormat uses curly braces to identify a placeholder:  The arguments on the right side of this window can be referenced in a template as follows:
{Person}, {Date}, {Inventory}

Many .NET objects can be formatted in a specific or custom way by using a ""format string"", which is any text that comes after a colon : in a placeholder:
Long date format: {Date:D}
Short date format: {Date:d}
Custom format: {Date:""today is"" dddd, ""the"" d ""of"" MMMM}

For more information on Composite Formatting and standard formatting strings, please visit http://msdn.microsoft.com/en-us/library/txafckwd.aspx
" },

                { "Named Placeholders",
                  @"Named Placeholders
Placeholders can use the name of any property, method, or field:
{Person.Name.ToUpper} is {Person.Age} years old and he has {Person.Friends.Count} friends.

Nested properties can use: 
- dot-notation: {Person.Address.State}
- nested notation: {Person.Address:{State}}
- any mixture of the two: {Person.Address:{State.ToString:{ToUpper}} }
" },

                { "Pluralization, Grammatical Numbers, and Gender Conjugation",
                  @"Pluralization, Grammatical Numbers, and Gender Conjugation
Many languages have specific and complex rules for pluralization and gender conjugation.  It is typically difficult to use templates and still use correct conjugation.  However, SmartFormat has a library of rules for hundreds of languages, and has an extremely simple syntax for choosing the correct word based on a value!

In English, there are only 2 plural forms: singular and plural.  You can specify a format string with both words, and the correct word will be chosen:
{Person.Random}: {Person.Random:singular|plural}

Example:
There {Person.Random:is|are} {Person.Random} {Person.Random:item|items} remaining.
" },

                { "List Formatting",
                  @"<!-- Pay attention to the ending |}} token -->
<Items count=""{Inventory.Count}"">
{Inventory:
	<Item name=""{Name}"" price=""{Price:c}"" index=""{Index}"" components=""{Components.Count}"">
	{Components:
	    <Component name=""{Name}"" count=""{Count}"" />
	|}
	</Item>
|}
</Items>
" },
            };

            var listObjects = examples.Cast <object>().ToArray();

            this.lstExamples.Items.AddRange(listObjects);
            this.lstExamples.SelectedIndex = 0;
        }
コード例 #6
0
ファイル: BaseDac.cs プロジェクト: lighteach/TestShoppingMall
        public string MakeSerialParam(Dictionary <string, string> dict)
        {
            string strRtn = string.Join("&", dict.Cast <KeyValuePair <string, string> >()
                                        .Select(kv => string.Format("{0}={1}", kv.Key, kv.Value))
                                        .ToArray());

            return(strRtn);
        }
コード例 #7
0
        /// <summary>
        /// Sets the stock data segments which are present in this file
        /// </summary>
        /// <typeparam name="T">The derived data point type</typeparam>
        /// <typeparam name="U">The base data point type</typeparam>
        /// <typeparam name="V">The processing state type</typeparam>
        /// <param name="segments">The set of segments to specify for this file</param>
        /// <returns>The data sets as an interface</returns>
        public static Dictionary <string, List <StockDataInterface> > CastToInterface(Dictionary <string, List <StockDataSetDerived <T, U, V> > > segments)
        {
            Dictionary <string, List <StockDataInterface> > castedSeg = segments.Cast <KeyValuePair <string, List <StockDataSetDerived <T, U, V> > > >().ToDictionary(
                (KeyValuePair <string, List <StockDataSetDerived <T, U, V> > > pair) => { return((string)pair.Key); },
                (KeyValuePair <string, List <StockDataSetDerived <T, U, V> > > pair) => { return(pair.Value.ConvertAll((x) => { return (StockDataInterface)x; })); }
                );

            return(castedSeg);
        }
コード例 #8
0
        public void ExtensionMethodForCastOneDictToAnotherTest()
        {
            // from int-int to string-long
            var source = new Dictionary <int, int> {
                { 1, 1 }, { 2, 2 }, { 3, 3 }
            }.AsReadOnlyDictionary();
            var target = source.Cast <int, int, int, dynamic>();

            target.ShouldNotBeNull();
            target.Count.ShouldBe(3);
        }
コード例 #9
0
ファイル: sort.cs プロジェクト: gurpartb/kattis
        static void Main(string[] args)
        {
            Dictionary <int, Num> counter = ReadData();

            Dictionary <int, Num> .ValueCollection vals = counter.Values;

            List <Num> list = vals.Cast <Num>().ToList();

            list = list.OrderBy(num => num.Index).ToList();

            list = list.OrderBy(num => num.Count * -1).ToList();

            foreach (var num in list)
            {
                Print(num);
            }
        }
コード例 #10
0
        private void TestCommand(IPlayer player, string command, string[] args)
        {
            player.Reply("Test successful!");


            Dictionary<string, string> parameters = new Dictionary<string, string>();

            parameters.Add("SteamID", "test123");
            parameters.Add("_id", "5c94bf6dc20a301b1829ba0b");

            string[] body = string.Join("&", parameters.Cast<string>().Select(key => string.Format("{0}={1}", key, source[key]));

            webrequest.Enqueue("http://localhost:3000/User", body, (code, response) =>
            {
                if (code != 200 || response == null)
                {
                    Puts($"error 400");
                    return;
                }
                Puts($"{response}");
            }, this, RequestMethod.PUT);
        }
コード例 #11
0
        private void SetupExecutionMonitors()
        {
            IDictionary <Guid, string> maNames = new Dictionary <Guid, string>();

            try
            {
                ConfigClient c = App.GetDefaultConfigClient();
                Debug.WriteLine("Getting management agent names");
                c.InvokeThenClose(x => maNames = x.GetManagementAgentNameIDs());
                Debug.WriteLine("Got management agent names");
                this.ExecutionMonitor = new ExecutionMonitorsViewModel(maNames.Cast <object>().ToList());
            }
            catch (EndpointNotFoundException ex)
            {
                Trace.WriteLine(ex.ToString());
                MessageBox.Show($"Could not contact the AutoSync service. The execution monitor could not be set up.", "AutoSync service unavailable", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Could not setup execution monitors");
                Trace.WriteLine(ex.ToString());
                MessageBox.Show($"Could not setup the execution monitor\n\n{ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #12
0
        public override void ExecuteCmdlet()
        {
            this._Helper = new AEMHelper((err) => this.WriteError(err), (msg) => this.WriteVerbose(msg), (msg) => this.WriteWarning(msg),
                                         this.CommandRuntime.Host.UI, AzureSession.Instance.ClientFactory.CreateArmClient <StorageManagementClient>(DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager), this.DefaultContext.Subscription);

            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                this._Helper.WriteVerbose("Retrieving VM...");

                var selectedVM       = ComputeClient.ComputeManagementClient.VirtualMachines.Get(this.ResourceGroupName, this.VMName);
                var selectedVMStatus = ComputeClient.ComputeManagementClient.VirtualMachines.GetWithInstanceView(this.ResourceGroupName, this.VMName).Body.InstanceView;

                if (selectedVM == null)
                {
                    var subscriptionId = this.DefaultContext.Subscription.Id;
                    this._Helper.WriteError("No virtual machine with name {0} in resource group {1} in subscription {2} found", this.VMName, this.ResourceGroupName, subscriptionId);
                    return;
                }

                var osdisk = selectedVM.StorageProfile.OsDisk;

                if (String.IsNullOrEmpty(this.OSType))
                {
                    this.OSType = osdisk.OsType.ToString();
                }
                if (String.IsNullOrEmpty(this.OSType))
                {
                    this._Helper.WriteError("Could not determine Operating System of the VM. Please provide the Operating System type ({0} or {1}) via parameter OSType",
                                            AEMExtensionConstants.OSTypeWindows, AEMExtensionConstants.OSTypeLinux);
                    return;
                }

                var disks = selectedVM.StorageProfile.DataDisks;

                var sapmonPublicConfig  = new List <KeyValuePair>();
                var sapmonPrivateConfig = new List <KeyValuePair>();
                var cpuOvercommit       = 0;
                var memOvercommit       = 0;
                var vmsize = selectedVM.HardwareProfile.VmSize;
                switch (vmsize)
                {
                case AEMExtensionConstants.VMSizeExtraSmall:
                case AEMExtensionConstants.VMSizeStandard_A0:
                case AEMExtensionConstants.VMSizeBasic_A0:
                    vmsize = "ExtraSmall (A0)";
                    WriteVerbose("VM Size is ExtraSmall - setting overcommitted setting");
                    cpuOvercommit = 1;
                    break;

                case "Small":
                    vmsize = "Small (A1)";
                    break;

                case "Medium":
                    vmsize = "Medium (A2)";
                    break;

                case "Large":
                    vmsize = "Large (A3)";
                    break;

                case "ExtraLarge":
                    vmsize = "ExtraLarge (A4)";
                    break;
                }
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vmsize", Value = vmsize
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vm.role", Value = "IaaS"
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vm.memory.isovercommitted", Value = memOvercommit
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "vm.cpu.isovercommitted", Value = cpuOvercommit
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "script.version", Value = AEMExtensionConstants.CurrentScriptVersion
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "verbose", Value = "0"
                });
                sapmonPublicConfig.Add(new KeyValuePair()
                {
                    Key = "href", Value = "http://aka.ms/sapaem"
                });

                var vmSLA = this._Helper.GetVMSLA(selectedVM);
                if (vmSLA.HasSLA)
                {
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "vm.sla.throughput", Value = vmSLA.TP
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "vm.sla.iops", Value = vmSLA.IOPS
                    });
                }

                // Get Disks
                var accounts = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                if (osdisk.ManagedDisk == null)
                {
                    var accountName = this._Helper.GetStorageAccountFromUri(osdisk.Vhd.Uri);
                    var storageKey  = this._Helper.GetAzureStorageKeyFromCache(accountName);
                    accounts.Add(accountName, storageKey);

                    this._Helper.WriteHost("[INFO] Adding configuration for OS disk");

                    var caching = osdisk.Caching;
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.name", Value = this._Helper.GetDiskName(osdisk.Vhd.Uri)
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.caching", Value = caching
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "osdisk.account", Value = accountName
                    });
                    if (this._Helper.IsPremiumStorageAccount(accountName))
                    {
                        WriteVerbose("OS Disk Storage Account is a premium account - adding SLAs for OS disk");
                        var sla = this._Helper.GetDiskSLA(osdisk);
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_PREMIUM
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.sla.throughput", Value = sla.TP
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.sla.iops", Value = sla.IOPS
                        });
                    }
                    else
                    {
                        WriteVerbose("OS Disk Storage Account is a standard account");
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_STANDARD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.connminute", Value = (accountName + ".minute")
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.connhour", Value = (accountName + ".hour")
                        });
                    }
                }
                else
                {
                    var osDiskMD = ComputeClient.ComputeManagementClient.Disks.Get(this._Helper.GetResourceGroupFromId(osdisk.ManagedDisk.Id),
                                                                                   this._Helper.GetResourceNameFromId(osdisk.ManagedDisk.Id));
                    if (osDiskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                    {
                        WriteVerbose("OS Disk Storage Account is a premium account - adding SLAs for OS disk");
                        var sla     = this._Helper.GetDiskSLA(osDiskMD.DiskSizeGB, null);
                        var caching = osdisk.Caching;
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.name", Value = this._Helper.GetResourceNameFromId(osdisk.ManagedDisk.Id)
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.caching", Value = caching
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_PREMIUM_MD
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.sla.throughput", Value = sla.TP
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "osdisk.sla.iops", Value = sla.IOPS
                        });
                    }
                    else
                    {
                        this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported. Extension will be installed but no disk metrics will be available.");
                    }
                }

                // Get Storage accounts from disks
                var diskNumber = 1;
                foreach (var disk in disks)
                {
                    if (disk.ManagedDisk != null)
                    {
                        var diskMD = ComputeClient.ComputeManagementClient.Disks.Get(this._Helper.GetResourceGroupFromId(disk.ManagedDisk.Id),
                                                                                     this._Helper.GetResourceNameFromId(disk.ManagedDisk.Id));

                        if (diskMD.Sku.Name == StorageAccountTypes.PremiumLRS)
                        {
                            this._Helper.WriteVerbose("Data Disk {0} is a Premium Managed Disk - adding SLAs for disk", diskNumber.ToString());
                            var sla       = this._Helper.GetDiskSLA(diskMD.DiskSizeGB, null);
                            var cachingMD = disk.Caching;
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.lun." + diskNumber, Value = disk.Lun
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.name." + diskNumber, Value = this._Helper.GetResourceNameFromId(disk.ManagedDisk.Id)
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.caching." + diskNumber, Value = cachingMD
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_PREMIUM_MD
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.sla.throughput." + diskNumber, Value = sla.TP
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.sla.iops." + diskNumber, Value = sla.IOPS
                            });
                            this._Helper.WriteVerbose("Done - Data Disk {0} is a Premium Managed Disk - adding SLAs for disk", diskNumber.ToString());
                        }
                        else
                        {
                            this._Helper.WriteWarning("[WARN] Standard Managed Disks are not supported. Extension will be installed but no disk metrics will be available.");
                        }
                    }
                    else
                    {
                        var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri);
                        if (!accounts.ContainsKey(accountName))
                        {
                            var storageKey = this._Helper.GetAzureStorageKeyFromCache(accountName);
                            accounts.Add(accountName, storageKey);
                        }

                        this._Helper.WriteHost("[INFO] Adding configuration for data disk {0}", disk.Name);
                        var caching = disk.Caching;
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.lun." + diskNumber, Value = disk.Lun
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.name." + diskNumber, Value = this._Helper.GetDiskName(disk.Vhd.Uri)
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.caching." + diskNumber, Value = caching
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = "disk.account." + diskNumber, Value = accountName
                        });

                        if (this._Helper.IsPremiumStorageAccount(accountName))
                        {
                            this._Helper.WriteVerbose("Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());
                            var sla = this._Helper.GetDiskSLA(disk);
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_PREMIUM
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.sla.throughput." + diskNumber, Value = sla.TP
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.sla.iops." + diskNumber, Value = sla.IOPS
                            });
                            this._Helper.WriteVerbose("Done - Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());
                        }
                        else
                        {
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_STANDARD
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.connminute." + diskNumber, Value = (accountName + ".minute")
                            });
                            sapmonPublicConfig.Add(new KeyValuePair()
                            {
                                Key = "disk.connhour." + diskNumber, Value = (accountName + ".hour")
                            });
                        }
                    }
                    diskNumber += 1;
                }

                //Check storage accounts for analytics
                foreach (var account in accounts)
                {
                    this._Helper.WriteVerbose("Testing Storage Metrics for {0}", account.Key);

                    var storage = this._Helper.GetStorageAccountFromCache(account.Key);

                    if (!this._Helper.IsPremiumStorageAccount(storage))
                    {
                        if (!this.SkipStorage.IsPresent)
                        {
                            var currentConfig = this._Helper.GetStorageAnalytics(storage.Name);

                            if (!this._Helper.CheckStorageAnalytics(storage.Name, currentConfig))
                            {
                                this._Helper.WriteHost("[INFO] Enabling Storage Account Metrics for storage account {0}", storage.Name);

                                // Enable analytics on storage accounts
                                this.SetStorageAnalytics(storage.Name);
                            }
                        }

                        var endpoint  = this._Helper.GetAzureSAPTableEndpoint(storage);
                        var hourUri   = endpoint + "$MetricsHourPrimaryTransactionsBlob";
                        var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob";

                        this._Helper.WriteHost("[INFO] Adding Storage Account Metric information for storage account {0}", storage.Name);

                        sapmonPrivateConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".hour.key"), Value = account.Value
                        });
                        sapmonPrivateConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".minute.key"), Value = account.Value
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".hour.uri"), Value = hourUri
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".minute.uri"), Value = minuteUri
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".hour.name"), Value = storage.Name
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".minute.name"), Value = storage.Name
                        });
                    }
                    else
                    {
                        this._Helper.WriteHost("[INFO] {0} is of type {1} - Storage Account Metrics are not available for Premium Type Storage.", storage.Name, storage.SkuName());
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".hour.ispremium"), Value = 1
                        });
                        sapmonPublicConfig.Add(new KeyValuePair()
                        {
                            Key = ((storage.Name) + ".minute.ispremium"), Value = 1
                        });
                    }
                }

                WriteVerbose("Chechking if WAD needs to be configured");
                // Enable VM Diagnostics
                if (this.EnableWAD.IsPresent)
                {
                    this._Helper.WriteHost("[INFO] Enabling IaaSDiagnostics for VM {0}", selectedVM.Name);
                    KeyValuePair wadstorage = null;
                    if (String.IsNullOrEmpty(this.WADStorageAccountName))
                    {
                        KeyValuePair <string, string>?wadstorageTemp = accounts.Cast <KeyValuePair <string, string>?>().
                                                                       FirstOrDefault(accTemp => !this._Helper.IsPremiumStorageAccount(accTemp.Value.Key));
                        if (wadstorageTemp.HasValue)
                        {
                            wadstorage = new KeyValuePair(wadstorageTemp.Value.Key, wadstorageTemp.Value.Value);
                        }
                    }
                    else
                    {
                        wadstorage = new KeyValuePair(this.WADStorageAccountName, this._Helper.GetAzureStorageKeyFromCache(WADStorageAccountName));
                    }

                    if (wadstorage == null)
                    {
                        this._Helper.WriteError("A standard storage account is required. Please use parameter WADStorageAccountName to specify a standard storage account you want to use for this VM.");
                        return;
                    }

                    selectedVM = SetAzureVMDiagnosticsExtensionC(selectedVM, selectedVMStatus, wadstorage.Key, wadstorage.Value as string);

                    var storage  = this._Helper.GetStorageAccountFromCache(wadstorage.Key);
                    var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage);
                    var wadUri   = endpoint + AEMExtensionConstants.WadTableName;

                    sapmonPrivateConfig.Add(new KeyValuePair()
                    {
                        Key = "wad.key", Value = wadstorage.Value
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "wad.name", Value = wadstorage.Key
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "wad.isenabled", Value = 1
                    });
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "wad.uri", Value = wadUri
                    });
                }
                else
                {
                    sapmonPublicConfig.Add(new KeyValuePair()
                    {
                        Key = "wad.isenabled", Value = 0
                    });
                }

                ExtensionConfig jsonPublicConfig = new ExtensionConfig();
                jsonPublicConfig.Config          = sapmonPublicConfig;

                ExtensionConfig jsonPrivateConfig = new ExtensionConfig();
                jsonPrivateConfig.Config          = sapmonPrivateConfig;

                this._Helper.WriteHost("[INFO] Updating Azure Enhanced Monitoring Extension for SAP configuration - Please wait...");

                WriteVerbose("Installing AEM extension");

                Version aemVersion = this._Helper.GetExtensionVersion(selectedVM, selectedVMStatus, OSType, AEMExtensionConstants.AEMExtensionType[OSType], AEMExtensionConstants.AEMExtensionPublisher[OSType]);

                var op = this.VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultName[OSType],
                    new VirtualMachineExtension()
                {
                    Publisher = AEMExtensionConstants.AEMExtensionPublisher[OSType],
                    VirtualMachineExtensionType = AEMExtensionConstants.AEMExtensionType[OSType],
                    TypeHandlerVersion          = aemVersion.ToString(2),
                    Settings                = jsonPublicConfig,
                    ProtectedSettings       = jsonPrivateConfig,
                    Location                = selectedVM.Location,
                    AutoUpgradeMinorVersion = true,
                    ForceUpdateTag          = DateTime.Now.Ticks.ToString()
                }).GetAwaiter().GetResult();

                this._Helper.WriteHost("[INFO] Azure Enhanced Monitoring Extension for SAP configuration updated. It can take up to 15 Minutes for the monitoring data to appear in the SAP system.");
                this._Helper.WriteHost("[INFO] You can check the configuration of a virtual machine by calling the Test-AzureRmVMAEMExtension commandlet.");

                var result = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op);
                WriteObject(result);
            });
        }
コード例 #13
0
        private bool OrderHasBlocks()
        {
            var sumOfValue = _order.Cast <int>().Sum();

            return(sumOfValue > 0);
        }
コード例 #14
0
 IEnumerator IEnumerable.GetEnumerator() => competitors.Cast <object>().Union(features.Cast <object>()).GetEnumerator();
コード例 #15
0
        public override void ExecuteCmdlet()
        {
            this._Helper = new AEMHelper((err) => this.WriteError(err), (msg) => this.WriteVerbose(msg), (msg) => this.WriteWarning(msg),
                this.CommandRuntime.Host.UI, AzureSession.ClientFactory.CreateClient<StorageManagementClient>(DefaultProfile.Context, AzureEnvironment.Endpoint.ResourceManager), this.DefaultContext.Subscription);

            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                this._Helper.WriteVerbose("Retrieving VM...");

                var selectedVM = ComputeClient.ComputeManagementClient.VirtualMachines.Get(this.ResourceGroupName, this.VMName);
                var selectedVMStatus = ComputeClient.ComputeManagementClient.VirtualMachines.GetWithInstanceView(this.ResourceGroupName, this.VMName);

                if (selectedVM == null)
                {
                    var subscriptionId = this.DefaultContext.Subscription.Id;
                    this._Helper.WriteError("No virtual machine with name {0} in resource group {1} in subscription {2} found", this.VMName, this.ResourceGroupName, subscriptionId);
                    return;
                }

                var osdisk = selectedVM.StorageProfile.OsDisk;

                if (String.IsNullOrEmpty(this.OSType))
                {
                    this.OSType = osdisk.OsType;
                }
                if (String.IsNullOrEmpty(this.OSType))
                {
                    this._Helper.WriteError("Could not determine Operating System of the VM. Please provide the Operating System type ({0} or {1}) via parameter OSType",
                        AEMExtensionConstants.OSTypeWindows, AEMExtensionConstants.OSTypeLinux);
                    return;
                }

                var disks = selectedVM.StorageProfile.DataDisks;

                var sapmonPublicConfig = new List<KeyValuePair>();
                var sapmonPrivateConfig = new List<KeyValuePair>();
                var cpuOvercommit = 0;
                var memOvercommit = 0;
                var vmsize = selectedVM.HardwareProfile.VmSize;
                switch (vmsize)
                {
                    case AEMExtensionConstants.VMSizeExtraSmall:
                    case AEMExtensionConstants.VMSizeStandard_A0:
                    case AEMExtensionConstants.VMSizeBasic_A0:
                        vmsize = "ExtraSmall (A0)";
                        WriteVerbose("VM Size is ExtraSmall - setting overcommitted setting");
                        cpuOvercommit = 1;
                        break;
                    case "Small":
                        vmsize = "Small (A1)";
                        break;
                    case "Medium":
                        vmsize = "Medium (A2)";
                        break;
                    case "Large":
                        vmsize = "Large (A3)";
                        break;
                    case "ExtraLarge":
                        vmsize = "ExtraLarge (A4)";
                        break;
                }
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "vmsize", Value = vmsize });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "vm.memory.isovercommitted", Value = memOvercommit.ToString() });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "vm.cpu.isovercommitted", Value = cpuOvercommit.ToString() });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "script.version", Value = AEMExtensionConstants.CurrentScriptVersion });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "verbose", Value = "1" });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "href", Value = "http://aka.ms/sapaem" });

                var vmSLA = this._Helper.GetVMSLA(selectedVM);
                if (vmSLA.HasSLA)
                {
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "vm.sla.throughput", Value = vmSLA.TP });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "vm.sla.iops", Value = vmSLA.IOPS });
                }

                // Get Disks
                var accounts = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
                var accountName = this._Helper.GetStorageAccountFromUri(osdisk.Vhd.Uri);
                var storageKey = this._Helper.GetAzureStorageKeyFromCache(accountName);
                accounts.Add(accountName, storageKey);

                this._Helper.WriteHost("[INFO] Adding configuration for OS disk");

                var caching = osdisk.Caching;
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.name", Value = osdisk.Name });
                sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.caching", Value = caching });
                if (this._Helper.IsPremiumStorageAccount(accountName))
                {
                    WriteVerbose("OS Disk Storage Account is a premium account - adding SLAs for OS disk");
                    var sla = this._Helper.GetDiskSLA(osdisk);
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_PREMIUM });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.sla.throughput", Value = sla.TP });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.sla.iops", Value = sla.IOPS });
                }
                else
                {
                    WriteVerbose("OS Disk Storage Account is a standard account");
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.type", Value = AEMExtensionConstants.DISK_TYPE_STANDARD });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.connminute", Value = (accountName + ".minute") });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "osdisk.connhour", Value = (accountName + ".hour") });
                }

                // Get Storage accounts from disks
                var diskNumber = 1;
                foreach (var disk in disks)
                {
                    accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri);
                    if (!accounts.ContainsKey(accountName))
                    {
                        storageKey = this._Helper.GetAzureStorageKeyFromCache(accountName);
                        accounts.Add(accountName, storageKey);
                    }

                    this._Helper.WriteHost("[INFO] Adding configuration for data disk {0}", disk.Name);
                    caching = disk.Caching;
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.lun." + diskNumber, Value = disk.Lun.ToString() });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.name." + diskNumber, Value = disk.Name });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.caching." + diskNumber, Value = caching });

                    if (this._Helper.IsPremiumStorageAccount(accountName))
                    {
                        this._Helper.WriteVerbose("Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());
                        var sla = this._Helper.GetDiskSLA(disk);
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_PREMIUM });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.sla.throughput." + diskNumber, Value = sla.TP });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.sla.iops." + diskNumber, Value = sla.IOPS });
                        this._Helper.WriteVerbose("Done - Data Disk {0} Storage Account is a premium account - adding SLAs for disk", diskNumber.ToString());

                    }
                    else
                    {
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.type." + diskNumber, Value = AEMExtensionConstants.DISK_TYPE_STANDARD });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.connminute." + diskNumber, Value = (accountName + ".minute") });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = "disk.connhour." + diskNumber, Value = (accountName + ".hour") });
                    }

                    diskNumber += 1;
                }

                //Check storage accounts for analytics
                foreach (var account in accounts)
                {
                    this._Helper.WriteVerbose("Testing Storage Metrics for {0}", account.Key);

                    var storage = this._Helper.GetStorageAccountFromCache(account.Key);

                    if (!this._Helper.IsPremiumStorageAccount(storage))
                    {
                        if (!this.SkipStorage.IsPresent)
                        {
                            var currentConfig = this._Helper.GetStorageAnalytics(storage.Name);

                            if (!this._Helper.CheckStorageAnalytics(storage.Name, currentConfig))
                            {
                                this._Helper.WriteHost("[INFO] Enabling Storage Account Metrics for storage account {0}", storage.Name);

                                // Enable analytics on storage accounts
                                this.SetStorageAnalytics(storage.Name);
                            }
                        }

                        var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage);
                        var hourUri = endpoint + "$MetricsHourPrimaryTransactionsBlob";
                        var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob";

                        this._Helper.WriteHost("[INFO] Adding Storage Account Metric information for storage account {0}", storage.Name);

                        sapmonPrivateConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".hour.key"), Value = account.Value });
                        sapmonPrivateConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".minute.key"), Value = account.Value });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".hour.uri"), Value = hourUri });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".minute.uri"), Value = minuteUri });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".hour.name"), Value = storage.Name });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".minute.name"), Value = storage.Name });
                    }
                    else
                    {
                        this._Helper.WriteHost("[INFO] {0} is of type {1} - Storage Account Metrics are not available for Premium Type Storage.", storage.Name, storage.AccountType.Value.ToString());
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".hour.ispremium"), Value = "1" });
                        sapmonPublicConfig.Add(new KeyValuePair() { Key = ((storage.Name) + ".minute.ispremium"), Value = "1" });
                    }
                }

                WriteVerbose("Chechking if WAD needs to be configured");
                // Enable VM Diagnostics
                if (!this.DisableWAD.IsPresent)
                {
                    this._Helper.WriteHost("[INFO] Enabling IaaSDiagnostics for VM {0}", selectedVM.Name);
                    KeyValuePair wadstorage = null;
                    if (String.IsNullOrEmpty(this.WADStorageAccountName))
                    {
                        KeyValuePair<string, string>? wadstorageTemp = accounts.Cast<KeyValuePair<string, string>?>().
                            FirstOrDefault(accTemp => !this._Helper.IsPremiumStorageAccount(accTemp.Value.Key));
                        if (wadstorageTemp.HasValue)
                        {
                            wadstorage = new KeyValuePair(wadstorageTemp.Value.Key, wadstorageTemp.Value.Value);
                        }
                    }
                    else
                    {
                        wadstorage = new KeyValuePair(this.WADStorageAccountName, this._Helper.GetAzureStorageKeyFromCache(WADStorageAccountName));
                    }

                    if (wadstorage == null)
                    {
                        this._Helper.WriteError("A Standard Storage Account is required.");
                        return;
                    }

                    selectedVM = SetAzureVMDiagnosticsExtensionC(selectedVM, wadstorage.Key, wadstorage.Value);

                    var storage = this._Helper.GetStorageAccountFromCache(wadstorage.Key);
                    var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage);
                    var wadUri = endpoint + AEMExtensionConstants.WadTableName;

                    sapmonPrivateConfig.Add(new KeyValuePair() { Key = "wad.key", Value = wadstorage.Value });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "wad.name", Value = wadstorage.Key });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "wad.isenabled", Value = "1" });
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "wad.uri", Value = wadUri });
                }
                else
                {
                    sapmonPublicConfig.Add(new KeyValuePair() { Key = "wad.isenabled", Value = "0" });
                }

                ExtensionConfig jsonPublicConfig = new ExtensionConfig();
                jsonPublicConfig.Config = sapmonPublicConfig;

                ExtensionConfig jsonPrivateConfig = new ExtensionConfig();
                jsonPrivateConfig.Config = sapmonPrivateConfig;

                this._Helper.WriteHost("[INFO] Updating Azure Enhanced Monitoring Extension for SAP configuration - Please wait...");

                WriteVerbose("Installing AEM extension");
                var op = this.VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync(
                    this.ResourceGroupName, this.VMName, AEMExtensionConstants.AEMExtensionDefaultName[OSType],
                    new VirtualMachineExtension()
                    {
                        Publisher = AEMExtensionConstants.AEMExtensionPublisher[OSType],
                        VirtualMachineExtensionType = AEMExtensionConstants.AEMExtensionType[OSType],
                        TypeHandlerVersion = AEMExtensionConstants.AEMExtensionVersion[OSType],
                        Settings = jsonPublicConfig,
                        ProtectedSettings = jsonPrivateConfig,
                        Location = selectedVM.Location,
                        AutoUpgradeMinorVersion = true
                    }).GetAwaiter().GetResult();

                this._Helper.WriteHost("[INFO] Azure Enhanced Monitoring Extension for SAP configuration updated. It can take up to 15 Minutes for the monitoring data to appear in the SAP system.");
                this._Helper.WriteHost("[INFO] You can check the configuration of a virtual machine by calling the Test-AzureRmVMAEMExtension commandlet.");

                var result = Mapper.Map<PSAzureOperationResponse>(op);
                WriteObject(result);
            });
        }
コード例 #16
0
        private void LoadExamples()
        {
            this.lstExamples.DisplayMember = "Key";
            //this.lstExamples.ValueMember = "Value";
            var examples = new Dictionary<string, string> {
{"Basics of SmartFormat", 
@"Basics of SmartFormat
Similar to String.Format, SmartFormat uses curly braces to identify a placeholder:  The arguments on the right side of this window can be referenced in a template as follows:
{Person}, {Date}, {Inventory}

Many .NET objects can be formatted in a specific or custom way by using a ""format string"", which is any text that comes after a colon : in a placeholder:
Long date format: {Date:D}
Short date format: {Date:d}
Custom format: {Date:""today is"" dddd, ""the"" d ""of"" MMMM}

For more information on Composite Formatting and standard formatting strings, please visit http://msdn.microsoft.com/en-us/library/txafckwd.aspx
"},

{"Named Placeholders", 
@"Named Placeholders
Placeholders can use the name of any property, method, or field:
{Person.Name.ToUpper} is {Person.Age} years old and he has {Person.Friends.Count} friends.

Nested properties can use: 
- dot-notation: {Person.Address.State}
- nested notation: {Person.Address:{State}}
- any mixture of the two: {Person.Address:{State.ToString:{ToUpper}} }
"},

{"Pluralization, Grammatical Numbers, and Gender Conjugation", 
@"Pluralization, Grammatical Numbers, and Gender Conjugation
Many languages have specific and complex rules for pluralization and gender conjugation.  It is typically difficult to use templates and still use correct conjugation.  However, SmartFormat has a library of rules for hundreds of languages, and has an extremely simple syntax for choosing the correct word based on a value!

In English, there are only 2 plural forms: singular and plural.  You can specify a format string with both words, and the correct word will be chosen:
{Person.Random}: {Person.Random:singular|plural}

Example:
There {Person.Random:is|are} {Person.Random} {Person.Random:item|items} remaining.
"},

{"List Formatting", 
@"<!-- Pay attention to the ending |}} token -->
<Items count=""{Inventory.Count}"">
{Inventory:
	<Item name=""{Name}"" price=""{Price:c}"" index=""{Index}"" components=""{Components.Count}"">
	{Components:
	    <Component name=""{Name}"" count=""{Count}"" />
	|}
	</Item>
|}
</Items>
"},
            };

	        var listObjects = examples.Cast<object>().ToArray();
	        this.lstExamples.Items.AddRange(listObjects);
	        this.lstExamples.SelectedIndex = 0;
        }
コード例 #17
0
 public List <Guild> GetGuildList()
 {
     return(GuildList.Cast <Guild>().Where(guild => guild.Searchable = true).ToList());
 }
コード例 #18
0
 public List <Party> GetPartyFinderList()
 {
     return(partyList.Cast <Party>().Where(party => party.PartyFinderId != 0).ToList());
 }
コード例 #19
0
        public override object ConvertToInternal(Dictionary <TKey, TValue> value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return(CollectionStringBegin + String.Join(",", value.Select(x => string.Format("{0}{1}{2}", x.Key, KeyValueSeparator, x.Value))) + CollectionStringEnd); //should format the map into a JSON-esque object
            }
            if (destinationType == typeof(byte[]))
            {
                var components = value;

                using (var bytes = new MemoryStream())
                {
                    //write the number of elements
                    var elements = (ushort)components.Count;
                    bytes.Write(BitConverter.GetBytes(elements), 0, 2);

                    foreach (var c in components)
                    {
                        var keyBytes = c.Key.ToBigEndian();

                        //key length
                        var keyLength = (ushort)keyBytes.Length;
                        bytes.Write(BitConverter.GetBytes(keyLength), 0, 2);

                        //key value
                        bytes.Write(keyBytes, 0, keyLength);

                        var valueBytes = c.Value.ToBigEndian();

                        // value length
                        var valueLength = (ushort)valueBytes.Length;
                        bytes.Write(BitConverter.GetBytes(valueLength), 0, 2);

                        // value
                        bytes.Write(valueBytes, 0, valueLength);
                    }

                    return(bytes.ToArray());
                }
            }

            if (destinationType == typeof(KeyValuePair <CassandraObject, CassandraObject>[]))
            {
                return(value.ToArray());
            }

            if (destinationType == typeof(object[]))
            {
                return(value.Cast <object>().ToArray());
            }

            if (destinationType == typeof(List <KeyValuePair <CassandraObject, CassandraObject> >) || destinationType == typeof(List <KeyValuePair <TKey, TValue> >))
            {
                return(value.ToList());
            }

            if (destinationType == typeof(Dictionary <TKey, TValue>) ||
                destinationType == typeof(Dictionary <CassandraObject, CassandraObject>))
            {
                return(value);
            }

            if (destinationType == typeof(List <object>))
            {
                return(value.Cast <object>().ToList());
            }

            return(null);
        }
コード例 #20
0
        private void LoadExamples()
        {
            this.lstExamples.DisplayMember = "Key";
            //this.lstExamples.ValueMember = "Value";
            var examples = new Dictionary <string, string> {
                { "Basics of SmartFormat",
                  @"Basics of SmartFormat
Similar to String.Format, SmartFormat uses curly braces to identify a placeholder:  The arguments on the right side of this window can be referenced in a template as follows:
{Person}, {Date}

Many .NET objects can be formatted in a specific or custom way by using a ""format string"", which is any text that comes after a colon : in a placeholder:
Long date format: {Date:D}
Short date format: {Date:d}
Custom format: {Date:""today is"" dddd, ""the"" d ""of"" MMMM}

Also works with DateTimeOffset types: 
Yesterday Local Time: {DateTimeOffset}
Yesterday Universal Time: {DateTimeOffset.UtcNow.DateTime}
Express Local Time offset to UTC with TimeFormatter: {DateTimeOffset.Offset:time(hours noless)}

For more information on Composite Formatting and standard formatting strings, please visit https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting
" },

                { "Named Placeholders",
                  @"Named Placeholders
Placeholders can use the name of any property, method, or field:
{Person.Name.ToUpper} is {Person.Age} years old and he has {Person.Friends.Count} friends.

Nested properties can use: 
- dot-notation: {Person.Address.State}
- nested notation: {Person.Address:{State}}
- any mixture of the two: {Person.Address:{State.ToString:{ToUpper}} }
" },

                { "Pluralization, Grammatical Numbers, and Gender Conjugation",
                  @"Pluralization, Grammatical Numbers, and Gender Conjugation
Many languages have specific and complex rules for pluralization and gender conjugation.  It is typically difficult to use templates and still use correct conjugation.  However, SmartFormat has a library of rules for hundreds of languages, and has an extremely simple syntax for choosing the correct word based on a value!

In English, there are only 2 plural forms: singular and plural.  You can specify a format string with both words, and the correct word will be chosen:
{Person.Random}: {Person.Random:singular|plural}

Example:
There {Person.Random:is|are} {Person.Random} {Person.Random:item|items} remaining.
" },

                { "List Formatting",
                  @"<!-- Curly braces can be escaped with a backslash -->
<Items count=""{Inventory.Count}"">
{Inventory:
    <Item name=""{Name}"" price=""{Price:c}"" index=""{Index}"" components=""{Components.Count}"">
    {Components:
        <Component name=""{Name}"" count=""{Count}"" />
    |}
    </Item>
|}
</Items>
" },
                { "Xml Source",
                  @"It is possible to format Xml as input argument
Example:
  There are {Xml.Person.Count} people: {Xml.Person: {FirstName}|,|, and}
  #1:  {Xml.Person.0: {FirstName}'s phone number is {Phone}}
  #2:  {Xml.Person.1: {FirstName}'s phone number is {Phone}}
" },
            };

            var listObjects = examples.Cast <object>().ToArray();

            this.lstExamples.Items.AddRange(listObjects);
            this.lstExamples.SelectedIndex = 0;
        }