text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```smalltalk
using System;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class Path
{
[XmlAttribute("Path")]
public string Value { get; set; }
public static implicit operator String(Path path)
{
return path.Value;
}
public static implicit operator Path(string path)
{
return new Path() { Value = path };
}
public override string ToString()
{
return Value;
}
public override bool Equals(object obj)
{
var path = obj as Path;
if (path == null)
return false;
return Value == path.Value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
}
``` | /content/code_sandbox/LabXml/Lab/Path.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 153 |
```smalltalk
using System;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class Domain
{
private string name;
[XmlAttribute]
public string Name
{
get { return name; }
set { name = value; }
}
private User administrator;
public User Administrator
{
get { return administrator; }
set { administrator = value; }
}
public System.Management.Automation.PSCredential GetCredential()
{
var userName = string.Format(@"{0}\{1}", name, Administrator.UserName);
var securePassword = new System.Security.SecureString();
securePassword.AppendString(Administrator.Password);
var cred = new System.Management.Automation.PSCredential(userName, securePassword);
return cred;
}
public override string ToString()
{
return name;
}
}
}
``` | /content/code_sandbox/LabXml/Lab/Domain.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 178 |
```smalltalk
using System;
using System.Collections.Generic;
using AutomatedLab.Azure;
namespace AutomatedLab
{
[Serializable]
public class AzureSettings
{
private List<AzureSubscription> subscriptions;
private AzureSubscription defaultSubscription;
private string azureRmProfilePath;
private string subscriptionFileContent;
private List<AzureLocation> locations;
private AzureRmStorageAccount defaultStorageAccount;
private AzureRmResourceGroup defaultResourceGroup;
private string defaultStorageAccountKey;
private AzureLocation defaultLocation;
private string vnetConfig;
private List<AzureRmStorageAccount> storageAccounts;
private List<AzureOSImage> vmImages;
private List<AzureVirtualMachine> virtualMachines;
private List<AzureRmVmSize> roleSizes;
private List<AzureRmResourceGroup> resourceGroups;
private List<string> vmDisks;
private string defaultRoleSize;
private string labSourcesStorageAccountName;
private string labSourcesResourceGroupName;
private int loadBalancerPortCounter;
public int LoadBalancerPortCounter
{
get { return loadBalancerPortCounter; }
set { loadBalancerPortCounter = value; }
}
public string AutoShutdownTime {get; set;}
public string AutoShutdownTimeZone { get; set; }
public bool AllowBastionHost {get; set; }
public string Environment { get; set; }
public bool IsAzureStack { get; set; }
public string LabSourcesResourceGroupName
{
get { return labSourcesResourceGroupName; }
set { labSourcesResourceGroupName = value; }
}
public string LabSourcesStorageAccountName
{
get { return labSourcesStorageAccountName; }
set { labSourcesStorageAccountName = value; }
}
public List<AzureRmStorageAccount> StorageAccounts
{
get { return storageAccounts; }
set { storageAccounts = value; }
}
public string AzureProfilePath
{
get { return azureRmProfilePath; }
set { azureRmProfilePath = value; }
}
public string SubscriptionFileContent
{
get { return subscriptionFileContent; }
set { subscriptionFileContent = value; }
}
public string VnetConfig
{
get { return vnetConfig; }
set { vnetConfig = value; }
}
public AzureLocation DefaultLocation
{
get { return defaultLocation; }
set { defaultLocation = value; }
}
public string DefaultStorageAccountKey
{
get { return defaultStorageAccountKey; }
set { defaultStorageAccountKey = value; }
}
public List<AzureOSImage> VmImages
{
get { return vmImages; }
set { vmImages = value; }
}
public List<AzureVirtualMachine> VirtualMachines
{
get { return virtualMachines; }
set { virtualMachines = value; }
}
public AzureRmStorageAccount DefaultStorageAccount
{
get { return defaultStorageAccount; }
set { defaultStorageAccount = value; }
}
public AzureRmResourceGroup DefaultResourceGroup
{
get { return defaultResourceGroup; }
set { defaultResourceGroup = value; }
}
public List<AzureSubscription> Subscriptions
{
get { return subscriptions; }
set { subscriptions = NonEmptyList<AzureSubscription>(value); }
}
public AzureSubscription DefaultSubscription
{
get { return defaultSubscription; }
set { defaultSubscription = value; }
}
public List<AzureLocation> Locations
{
get { return locations; }
set { locations = value; }
}
public List<AzureRmVmSize> RoleSizes
{
get { return roleSizes; }
set { roleSizes = value; }
}
public List<AzureRmResourceGroup> ResourceGroups
{
get { return resourceGroups; }
set { resourceGroups = NonEmptyList<AzureRmResourceGroup>(value); }
}
public List<string> VmDisks
{
get { return vmDisks; }
set { vmDisks = value; }
}
public string DefaultRoleSize
{
get { return defaultRoleSize; }
set { defaultRoleSize = value; }
}
public AzureSettings()
{
locations = new List<AzureLocation>();
storageAccounts = new List<AzureRmStorageAccount>();
vmImages = new List<AzureOSImage>();
roleSizes = new List<AzureRmVmSize>();
resourceGroups = new List<AzureRmResourceGroup>();
subscriptions = new List<AzureSubscription>();
vmDisks = new List<string>();
Environment = "AzureCloud"; // Default environment for public cloud
// Start port counter above well-known ports
LoadBalancerPortCounter = 5000;
}
protected List<T> NonEmptyList<T>(List<T> value)
{
if (value == null)
return new List<T>();
else
return value;
}
}
}
``` | /content/code_sandbox/LabXml/Lab/AzureConfiguration.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,101 |
```smalltalk
using System;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class VMWareConfiguration
{
private string dataCenterName;
private string dataStoreName;
private string resourcePoolName;
private string clusterName;
private string vCenterServerName;
private string credential;
private object dataCenter;
private object network;
private object dataStore;
private object resourcePool;
private object cluster;
public string DataCenterName
{
get { return dataCenterName; }
set { dataCenterName = value; }
}
public string DataStoreName
{
get { return dataStoreName; }
set { dataStoreName = value; }
}
public string ResourcePoolName
{
get { return resourcePoolName; }
set { resourcePoolName = value; }
}
public string ClusterName
{
get { return clusterName; }
set { clusterName = value; }
}
public string VCenterServerName
{
get { return vCenterServerName; }
set { vCenterServerName = value; }
}
public string Credential
{
get { return credential; }
set { credential = value; }
}
[XmlIgnore]
public object DataCenter
{
get { return dataCenter; }
set { dataCenter = value; }
}
[XmlIgnore]
public object Network
{
get { return network; }
set { network = value; }
}
[XmlIgnore]
public object DataStore
{
get { return dataStore; }
set { dataStore = value; }
}
[XmlIgnore]
public object ResourcePool
{
get { return resourcePool; }
set { resourcePool = value; }
}
[XmlIgnore]
public object Cluster
{
get { return cluster; }
set { cluster = value; }
}
}
}
``` | /content/code_sandbox/LabXml/Lab/VMWareConfiguration.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 426 |
```smalltalk
using System;
namespace AutomatedLab.Azure
{
[Serializable]
public class AzureOSImage : CopiedObject<AzureOSImage>
{
public string Id { get; set; }
public string Location { get; set; }
public string Offer { get; set; }
public string PublisherName { get; set; }
public string Skus { get; set; }
public string Version { get; set; }
public string HyperVGeneration { get; set; }
public string AutomatedLabOperatingSystemName
{
get
{
return OsNameFromAzureString($"{Skus}_{PublisherName}");
}
}
public AzureOSImage() { }
public override string ToString()
{
return Offer;
}
private string OsNameFromAzureString(string azureSkuName)
{
// Return OS name AutomatedLab uses from one of the many, many, Azure SKU names
switch (azureSkuName.ToLower())
{
case your_sha256_hasherver":
return "Windows Server 2022 Datacenter";
case "windows-server-2022-g2_microsoftwindowsserver":
return "Windows Server 2022 Datacenter (Desktop Experience)";
case "windows-server-vnext-azure-edition_microsoftwindowsserver":
return "Windows Server 2025 Datacenter (Desktop Experience)";
case "windows-server-vnext-azure-edition-core_microsoftwindowsserver":
return "Windows Server 2025 Datacenter";
case "2012-datacenter_microsoftwindowsserver":
return "Windows Server 2012 Datacenter (Server with a GUI)";
case "2012-datacenter-gensecond_microsoftwindowsserver":
return "Windows Server 2012 Datacenter (Server with a GUI)";
case "2012-r2-datacenter_microsoftwindowsserver":
return "Windows Server 2012 R2 Datacenter (Server with a GUI)";
case "2012-r2-datacenter-gensecond_microsoftwindowsserver":
return "Windows Server R2 2012 Datacenter (Server with a GUI)";
case "2016-datacenter_microsoftwindowsserver":
return "Windows Server 2016 Datacenter (Desktop Experience)";
case "2016-datacenter-gensecond_microsoftwindowsserver":
return "Windows Server 2016 Datacenter (Desktop Experience)";
case "2016-datacenter-server-core_microsoftwindowsserver":
return "Windows Server 2016 Datacenter";
case "2016-datacenter-server-core-g2_microsoftwindowsserver":
return "Windows Server 2016 Datacenter";
case "2019-datacenter_microsoftwindowsserver":
return "Windows Server 2019 Datacenter (Desktop Experience)";
case "2019-datacenter-core_microsoftwindowsserver":
return "Windows Server 2019 Datacenter";
case "2019-datacenter-core-g2_microsoftwindowsserver":
return "Windows Server 2019 Datacenter";
case "2019-datacenter-gensecond_microsoftwindowsserver":
return "Windows Server 2019 Datacenter (Desktop Experience)";
case "2019-datacenter-gs_microsoftwindowsserver":
return "Windows Server 2019 Datacenter";
case "2019-datacenter-gs-g2_microsoftwindowsserver":
return "Windows Server 2019 Datacenter";
case "2022-datacenter_microsoftwindowsserver":
return "Windows Server 2022 Datacenter (Desktop Experience)";
case "2022-datacenter-azure-edition_microsoftwindowsserver":
return "Windows Server 2022 Datacenter (Desktop Experience)";
case "2022-datacenter-azure-edition-core_microsoftwindowsserver":
return "Windows Server 2022 Datacenter";
case "2022-datacenter-azure-edition-hotpatch_microsoftwindowsserver":
return "Windows Server 2022 Datacenter (Desktop Experience)";
case "2022-datacenter-core_microsoftwindowsserver":
return "Windows Server 2022 Datacenter";
case "2022-datacenter-core-g2_microsoftwindowsserver":
return "Windows Server 2022 Datacenter";
case "2022-datacenter-g2_microsoftwindowsserver":
return "Windows Server 2022 Datacenter (Desktop Experience)";
case "23h2-datacenter-core_microsoftwindowsserver":
return "Windows Server 2022 Datacenter";
case "23h2-datacenter-core-g2_microsoftwindowsserver":
return "Windows Server 2022 Datacenter";
case "2016-datacenter-gen2_microsoftwindowsserver":
return "Windows Server 2016 Datacenter (Desktop Experience)";
case "20_04-lts_canonical":
return "Ubuntu Server 20.04 LTS \"Focal Fossa\"";
case "20_04-lts-gen2_canonical":
return "Ubuntu Server 20.04 LTS \"Focal Fossa\"";
case "20_10-gen2_canonical":
return "Ubuntu Server 20.10 \"Groovy Gorilla\"";
case "22_04-lts_canonical":
return "Ubuntu Server 22.04 LTS \"Jammy Jellyfish\"";
case "22_04-lts-gen2_canonical":
return "Ubuntu Server 22.04 LTS \"Jammy Jellyfish\"";
case "23_04_canonical":
return "Ubuntu Server 23.04 \"Lunar Lobster\"";
case "23_04-gen2_canonical":
return "Ubuntu Server 23.04 \"Lunar Lobster\"";
case "23_10_canonical":
return "Ubuntu Server 23.10 \"Mantic Minotaur\"";
case "23_10-gen2_canonical":
return "Ubuntu Server 23.10 \"Mantic Minotaur\"";
case "7.4_redhat":
return "Red Hat Enterprise Linux 7.4";
case "7.5_redhat":
return "Red Hat Enterprise Linux 7.5";
case "7.6_redhat":
return "Red Hat Enterprise Linux 7.6";
case "7.7_redhat":
return "Red Hat Enterprise Linux 7.7";
case "7.8_redhat":
return "Red Hat Enterprise Linux 7.8";
case "74-gen2_redhat":
return "Red Hat Enterprise Linux 7.4";
case "75-gen2_redhat":
return "Red Hat Enterprise Linux 7.5";
case "76-gen2_redhat":
return "Red Hat Enterprise Linux 7.6";
case "77-gen2_redhat":
return "Red Hat Enterprise Linux 7.7";
case "78-gen2_redhat":
return "Red Hat Enterprise Linux 7.8";
case "79-gen2_redhat":
return "Red Hat Enterprise Linux 7.9";
case "7_9_redhat":
return "Red Hat Enterprise Linux 7.9";
case "8_redhat":
return "Red Hat Enterprise Linux 8.0";
case "8.1_redhat":
return "Red Hat Enterprise Linux 8.1";
case "8.2_redhat":
return "Red Hat Enterprise Linux 8.2";
case "810-gen2_redhat":
return "Red Hat Enterprise Linux 8.10";
case "81gen2_redhat":
return "Red Hat Enterprise Linux 8.1";
case "82gen2_redhat":
return "Red Hat Enterprise Linux 8.2";
case "83-gen2_redhat":
return "Red Hat Enterprise Linux 8.3";
case "84-gen2_redhat":
return "Red Hat Enterprise Linux 8.4";
case "85-gen2_redhat":
return "Red Hat Enterprise Linux 8.5";
case "86-gen2_redhat":
return "Red Hat Enterprise Linux 8.6";
case "87-gen2_redhat":
return "Red Hat Enterprise Linux 8.7";
case "88-gen2_redhat":
return "Red Hat Enterprise Linux 8.8";
case "89-gen2_redhat":
return "Red Hat Enterprise Linux 8.9";
case "8_10_redhat":
return "Red Hat Enterprise Linux 8.10";
case "8_3_redhat":
return "Red Hat Enterprise Linux 8.3";
case "8_4_redhat":
return "Red Hat Enterprise Linux 8.4";
case "8_5_redhat":
return "Red Hat Enterprise Linux 8.5";
case "8_6_redhat":
return "Red Hat Enterprise Linux 8.6";
case "8_7_redhat":
return "Red Hat Enterprise Linux 8.7";
case "8_8_redhat":
return "Red Hat Enterprise Linux 8.8";
case "8_9_redhat":
return "Red Hat Enterprise Linux 8.9";
case "90-gen2_redhat":
return "Red Hat Enterprise Linux 9.0";
case "91-gen2_redhat":
return "Red Hat Enterprise Linux 9.1";
case "92-gen2_redhat":
return "Red Hat Enterprise Linux 9.2";
case "93-gen2_redhat":
return "Red Hat Enterprise Linux 9.3";
case "94_gen2_redhat":
return "Red Hat Enterprise Linux 9.4";
case "9_0_redhat":
return "Red Hat Enterprise Linux 9.0";
case "9_1_redhat":
return "Red Hat Enterprise Linux 9.1";
case "9_2_redhat":
return "Red Hat Enterprise Linux 9.2";
case "9_3_redhat":
return "Red Hat Enterprise Linux 9.3";
case "9_4_redhat":
return "Red Hat Enterprise Linux 9.4";
case "6.10_openlogic":
return "CentOS 6.10";
case "6.9_openlogic":
return "CentOS 6.9";
case "7.3_openlogic":
return "CentOS 7.3";
case "7.4_openlogic":
return "CentOS 7.4";
case "7.5_openlogic":
return "CentOS 7.5";
case "7.6_openlogic":
return "CentOS 7.6";
case "7.7_openlogic":
return "CentOS 7.7";
case "7_4_openlogic":
return "CentOS 7.4";
case "7_4-gen2_openlogic":
return "CentOS 7.4";
case "7_5-gen2_openlogic":
return "CentOS 7.5";
case "7_6-gen2_openlogic":
return "CentOS 7.6";
case "7_7-gen2_openlogic":
return "CentOS 7.7";
case "7_8_openlogic":
return "CentOS 7.8";
case "7_8-gen2_openlogic":
return "CentOS 7.8";
case "7_9_openlogic":
return "CentOS 7.9";
case "7_9-gen2_openlogic":
return "CentOS 7.9";
case "8.0_openlogic":
return "CentOS 8.0";
case "8_0-gen2_openlogic":
return "CentOS 8.0";
case "8_1_openlogic":
return "CentOS 8.1";
case "8_1-gen2_openlogic":
return "CentOS 8.1";
case "8_2_openlogic":
return "CentOS 8.2";
case "8_2-gen2_openlogic":
return "CentOS 8.2";
case "8_3_openlogic":
return "CentOS 8.3";
case "8_3-gen2_openlogic":
return "CentOS 8.3";
case "8_4_openlogic":
return "CentOS 8.4";
case "8_4-gen2_openlogic":
return "CentOS 8.4";
case "8_5_openlogic":
return "CentOS 8.5";
case "8_5-gen2_openlogic":
return "CentOS 8.5";
case "kali-2023-3_kali-linux":
return "Kali Linux 2023.3";
case "kali-2023-4_kali-linux":
return "Kali Linux 2023.4";
case "19h1-ent-gensecond_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "19h1-entn-gensecond_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "19h1-pro-gensecond_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "19h1-pron-gensecond_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "19h2-pro-g2_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "19h2-pron-g2_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "20h2-ent_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "20h2-ent-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "20h2-entn_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "20h2-entn-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "rs1-enterprise_microsoftwindowsdesktop": // 1607
return "Windows 10 Enterprise";
case "rs1-enterprise-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "rs1-enterprisen_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "rs1-enterprisen-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "rs5-enterprise_microsoftwindowsdesktop": // 1809
return "Windows 10 Enterprise";
case "rs5-enterprise-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "rs5-enterprise-standard-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "rs5-enterprisen_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "rs5-enterprisen-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "rs5-enterprisen-standard-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "win10-21h2-ent_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "win10-21h2-ent-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "win10-21h2-ent-ltsc_microsoftwindowsdesktop":
return "Windows 10 Enterprise LTSC";
case "win10-21h2-ent-ltsc-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise LTSC";
case "win10-21h2-entn_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "win10-21h2-entn-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "win10-21h2-entn-ltsc_microsoftwindowsdesktop":
return "Windows 10 Enterprise N LTSC";
case "win10-21h2-entn-ltsc-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N LTSC";
case "win10-21h2-pro_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "win10-21h2-pro-g2_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "win10-21h2-pron_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "win10-21h2-pron-g2_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "win10-22h2-ent_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "win10-22h2-ent-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise";
case "win10-22h2-entn_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "win10-22h2-entn-g2_microsoftwindowsdesktop":
return "Windows 10 Enterprise N";
case "win10-22h2-pro_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "win10-22h2-pro-g2_microsoftwindowsdesktop":
return "Windows 10 Pro";
case "win10-22h2-pron_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "win10-22h2-pron-g2_microsoftwindowsdesktop":
return "Windows 10 Pro N";
case "win11-21h2-entn_microsoftwindowsdesktop":
return "Windows 11 Enterprise N";
case "win11-21h2-pron_microsoftwindowsdesktop":
return "Windows 11 Pro N";
case "win11-22h2-entn_microsoftwindowsdesktop":
return "Windows 11 Enterprise N";
case "win11-22h2-pron_microsoftwindowsdesktop":
return "Windows 11 Pro N";
case "win11-23h2-entn_microsoftwindowsdesktop":
return "Windows 11 Enterprise N";
case "win11-23h2-pron_microsoftwindowsdesktop":
return "Windows 11 Pro N";
case "win11-24h2-entn_microsoftwindowsdesktop":
return "Windows 11 Enterprise N";
case "win11-24h2-pron_microsoftwindowsdesktop":
return "Windows 11 Pro N";
case "win11-21h2-ent_microsoftwindowsdesktop":
return "Windows 11 Enterprise";
case "win11-21h2-pro_microsoftwindowsdesktop":
return "Windows 11 Pro";
case "win11-22h2-ent_microsoftwindowsdesktop":
return "Windows 11 Enterprise";
case "win11-22h2-pro_microsoftwindowsdesktop":
return "Windows 11 Pro";
case "win11-23h2-ent_microsoftwindowsdesktop":
return "Windows 11 Enterprise";
case "win11-23h2-pro_microsoftwindowsdesktop":
return "Windows 11 Pro";
case "win11-24h2-ent_microsoftwindowsdesktop":
return "Windows 11 Enterprise";
case "win11-24h2-pro_microsoftwindowsdesktop":
return "Windows 11 Pro";
default:
return string.Empty;
}
}
}
}
``` | /content/code_sandbox/LabXml/Azure/AzureOSImage.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 4,163 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Linq;
namespace AutomatedLab
{
[Serializable]
public class Sources
{
private List<IsoImage> isos;
private Path unattendedXml;
public List<IsoImage> ISOs
{
get { return isos; }
set { isos = value; }
}
[XmlIgnore]
public List<OperatingSystem> AvailableOperatingSystems
{
get { return isos.Cast<IsoImage>().SelectMany(iso => iso.OperatingSystems).ToList(); }
}
public Path UnattendedXml
{
get { return unattendedXml; }
set { unattendedXml = value; }
}
public Sources()
{
isos = new List<IsoImage>();
}
}
[Serializable]
public class Target
{
private string path;
private int referenceDiskSizeInGB;
[XmlAttribute]
public string Path
{
get { return path; }
set { path = value; }
}
public int ReferenceDiskSizeInGB
{
get { return referenceDiskSizeInGB; }
set { referenceDiskSizeInGB = value; }
}
}
[Serializable]
public class MachineDefinitionFile
{
[XmlAttribute()]
public string Path { get; set; }
}
[Serializable]
public class DiskDefinitionFile
{
[XmlAttribute()]
public string Path { get; set; }
}
[Serializable]
public class Lab : XmlStore<Lab>
{
private string name;
private List<Domain> domains;
private List<Machine> machines;
private List<Disk> disks;
private List<VirtualNetwork> virtualNetworks;
private List<DiskDefinitionFile> diskDefinitionFiles;
private List<MachineDefinitionFile> machineDefinitionFiles;
private Sources sources;
private Target target;
private string labFilePath;
private long maxMemory;
private bool useStaticMemory;
private OperatingSystem defaultOperatingSystem;
private string defaultVirtualizationEngine;
private User defaultInstallationUserCredential;
private SerializableDictionary<string, string> notes;
private AzureSettings azureSettings;
private VMWareConfiguration vmwareSettings;
private Azure.AzureRm azureResources;
public List<Disk> Disks
{
get { return disks; }
set { disks = value; }
}
public List<Machine> Machines
{
get { return machines; }
set { machines = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public List<Domain> Domains
{
get { return domains; }
set { domains = value; }
}
public List<MachineDefinitionFile> MachineDefinitionFiles
{
get { return machineDefinitionFiles; }
set { machineDefinitionFiles = value; }
}
public Sources Sources
{
get { return sources; }
set { sources = value; }
}
public Target Target
{
get { return target; }
set { target = value; }
}
public List<VirtualNetwork> VirtualNetworks
{
get { return virtualNetworks; }
set { virtualNetworks = value; }
}
public string LabFilePath
{
get { return labFilePath; }
set { labFilePath = value; }
}
public string LabPath
{
get { return System.IO.Path.GetDirectoryName(labFilePath); }
}
public long MaxMemory
{
get { return maxMemory; }
set { maxMemory = value; }
}
public bool UseStaticMemory
{
get { return useStaticMemory; }
set { useStaticMemory = value; }
}
public OperatingSystem DefaultOperatingSystem
{
get { return defaultOperatingSystem; }
set { defaultOperatingSystem = value; }
}
public string DefaultVirtualizationEngine
{
get { return defaultVirtualizationEngine; }
set { defaultVirtualizationEngine = value; }
}
public User DefaultInstallationCredential
{
get { return defaultInstallationUserCredential; }
set { defaultInstallationUserCredential = value; }
}
public SerializableDictionary<string, string> Notes
{
get { return notes; }
set { notes = value; }
}
public List<DiskDefinitionFile> DiskDefinitionFiles
{
get { return diskDefinitionFiles; }
set { diskDefinitionFiles = value; }
}
public AzureSettings AzureSettings
{
get { return azureSettings; }
set { azureSettings = value; }
}
public VMWareConfiguration VMWareSettings
{
get { return vmwareSettings; }
set { vmwareSettings = value; }
}
public Azure.AzureRm AzureResources
{
get { return azureResources; }
set { azureResources = value; }
}
public Lab()
{
sources = new Sources();
target = new Target();
domains = new List<Domain>();
machineDefinitionFiles = new List<MachineDefinitionFile>();
diskDefinitionFiles = new List<DiskDefinitionFile>();
sources.ISOs = new List<IsoImage>();
virtualNetworks = new List<VirtualNetwork>();
notes = new SerializableDictionary<string, string>();
azureResources = new Azure.AzureRm();
}
public bool IsRootDomain(string domainName)
{
var rootDCs = Machines.Where(m => m.Roles.Where(r => r.Name == Roles.RootDC).Count() == 1);
if (rootDCs.Where(m => m.DomainName.ToLower() == domainName.ToLower()).Count() == 1)
return true;
else
return false;
}
public Domain GetParentDomain(string domainName)
{
domainName = domainName.ToLower();
if (Domains.Where(d => d.Name.ToLower() == domainName).Count() == 0)
throw new ArgumentException($"The domain {domainName} could not be found in the lab.");
var firstChildDcs = Machines.Where(m => m.Roles.Where(r => r.Name == Roles.FirstChildDC).Count() == 1);
if (IsRootDomain(domainName))
{
return domains.Where(d => d.Name.ToLower() == domainName.ToLower()).FirstOrDefault();
}
else
{
var parentDomainName = firstChildDcs.Where(m => m.DomainName.ToLower() == domainName.ToLower()).FirstOrDefault().Roles.Where(r => r.Name == Roles.FirstChildDC).FirstOrDefault().Properties["ParentDomain"];
return domains.Where(d => d.Name.ToLower() == parentDomainName.ToLower()).FirstOrDefault();
}
}
}
}
``` | /content/code_sandbox/LabXml/Lab/Lab.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,441 |
```smalltalk
using System;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Win32;
namespace AutomatedLab
{
[Serializable]
public class XmlStore<T> : ICloneable where T : class
{
public void ExportToRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(typeof(XmlStore<T>));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var sw = new StringWriter();
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Registry.CurrentUser.CreateSubKey(registryPath);
serializer.Serialize(sw, this, xmlNamespace);
key.SetValue(valueName, sw.ToString(), RegistryValueKind.String);
key.Close();
}
public byte[] Export()
{
var serializer = new XmlSerializer(typeof(T));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var stream = new MemoryStream();
serializer.Serialize(stream, this, xmlNamespace);
stream.Close();
return stream.ToArray();
}
public void Export(string path)
{
File.Delete(path);
var serializer = new XmlSerializer(typeof(T));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var fileStream = new FileStream(path, FileMode.CreateNew);
serializer.Serialize(fileStream, this, xmlNamespace);
fileStream.Close();
}
public static T Import(string path)
{
var serializer = new XmlSerializer(typeof(T));
T item = null;
var fileStream = File.OpenRead(path);
item = (T)serializer.Deserialize(fileStream);
fileStream.Close();
return item;
}
public static T Import(byte[] data)
{
var serializer = new XmlSerializer(typeof(T));
var stream = new MemoryStream(data);
var items = (T)serializer.Deserialize(stream);
stream.Close();
return items;
}
public static XmlStore<T> ImportFromRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(typeof(XmlStore<T>));
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Registry.CurrentUser.OpenSubKey(registryPath);
if (key == null)
throw new FileNotFoundException(string.Format("The registry key '{0}' does not exist", registryPath));
var value = key.GetValue(valueName);
if (value == null)
throw new FileNotFoundException(string.Format("The registry value '{0}' does not exist in key '{1}'", valueName, registryPath));
StringReader sr = new StringReader(value.ToString());
var item = (XmlStore<T>)serializer.Deserialize(sr);
sr.Close();
return item;
}
public object Clone()
{
var serializer = new XmlSerializer(typeof(T));
var stream = new MemoryStream();
serializer.Serialize(stream, this);
var item = (T)serializer.Deserialize(stream);
return item;
}
}
}
``` | /content/code_sandbox/LabXml/Stores/XmlStore.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 705 |
```smalltalk
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class ListXmlStore<T> : SerializableList<T>
{
public byte[] Export()
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var stream = new MemoryStream();
serializer.Serialize(stream, this, xmlNamespace);
stream.Close();
return stream.ToArray();
}
public void Export(string path)
{
File.Delete(path);
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var fileStream = new FileStream(path, FileMode.CreateNew);
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
serializer.Serialize(fileStream, this, xmlNamespace);
fileStream.Close();
}
public void ExportToRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var sw = new StringWriter();
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(registryPath);
serializer.Serialize(sw, this, xmlNamespace);
key.SetValue(valueName, sw.ToString(), Microsoft.Win32.RegistryValueKind.String);
key.Close();
}
public string ExportToString()
{
var serializer = new XmlSerializer(GetType());
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var sb = new StringBuilder();
var sw = new StringWriter();
serializer.Serialize(sw, this, xmlNamespace);
sw.Close();
return sb.ToString();
}
public static ListXmlStore<T> Import(byte[] data)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var stream = new MemoryStream(data);
var items = (ListXmlStore<T>)serializer.Deserialize(stream);
stream.Close();
return items;
}
public void AddFromFile(string path)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var fileStream = new FileStream(path, FileMode.Open);
AddRange((ListXmlStore<T>)serializer.Deserialize(fileStream));
fileStream.Close();
}
public static ListXmlStore<T> Import(string path)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
FileStream fileStream = new FileStream(path, FileMode.Open);
var items = (ListXmlStore<T>)serializer.Deserialize(fileStream);
fileStream.Close();
return items;
}
public static ListXmlStore<T> ImportFromRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(registryPath);
if (key == null)
throw new FileNotFoundException(string.Format("The registry key '{0}' does not exist", registryPath));
var value = key.GetValue(valueName);
if (value == null)
throw new FileNotFoundException(string.Format("The registry value '{0}' does not exist in key '{1}'", valueName, registryPath));
StringReader sr = new StringReader(value.ToString());
var items = (ListXmlStore<T>)serializer.Deserialize(sr);
sr.Close();
return items;
}
public static ListXmlStore<T> ImportFromString(string s)
{
var serializer = new XmlSerializer(typeof(ListXmlStore<T>));
var sr = new StringReader(s);
var items = (ListXmlStore<T>)serializer.Deserialize(sr);
sr.Close();
return items;
}
}
}
``` | /content/code_sandbox/LabXml/Stores/ListXmlStore.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 886 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Linq;
namespace AutomatedLab
{
[XmlRoot("List", Namespace = "")]
public class SerializableList<T>
: List<T>, IXmlSerializable
{
List<string> builtinProperties = new List<string>() { "Capacity", "Item" };
public DateTime Timestamp { get; set; }
public Guid ID { get; set; }
public List<string> Metadata { get; set; }
public SerializableList()
: base()
{
Metadata = new List<string>();
}
public SerializableList(IList<T> list)
: base(list)
{
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer itemSerializer = new XmlSerializer(typeof(T));
var propertyInfos = GetType().GetProperties().Where(pi => !builtinProperties.Contains(pi.Name));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (!reader.EOF)
{
var propertyInfo = propertyInfos.Where(pi => pi.Name == reader.Name).FirstOrDefault();
if (propertyInfo != null)
{
reader.ReadStartElement();
var serializer = new XmlSerializer(propertyInfo.PropertyType);
propertyInfo.SetValue(this, serializer.Deserialize(reader));
reader.ReadEndElement();
}
else
{
T item = (T)itemSerializer.Deserialize(reader);
Add(item);
if (reader.NodeType == System.Xml.XmlNodeType.EndElement)
reader.ReadEndElement();
reader.MoveToContent();
}
}
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer itemSerializer = new XmlSerializer(typeof(T));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var propertyInfos = GetType().GetProperties()
.Where(pi => pi.CanWrite && !builtinProperties.Contains(pi.Name)).ToList();
foreach (var propertyInfo in propertyInfos)
{
var serializer = new XmlSerializer(propertyInfo.PropertyType);
writer.WriteStartElement(propertyInfo.Name);
serializer.Serialize(writer, propertyInfo.GetValue(this), xmlNamespace);
writer.WriteEndElement();
}
foreach (T item in this)
{
itemSerializer.Serialize(writer, item, xmlNamespace);
}
}
#endregion
}
}
``` | /content/code_sandbox/LabXml/Stores/SerializableList.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 512 |
```smalltalk
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Linq;
namespace AutomatedLab
{
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
List<string> builtinProperties = new List<string>() { "Capacity", "Item" };
public DateTime Timestamp { get; set; }
public Guid ID { get; set; }
public List<string> Metadata { get; set; }
public SerializableDictionary()
: base()
{
Metadata = new List<string>();
}
public SerializableDictionary(IDictionary<TKey, TValue> dictionary)
: base(dictionary)
{
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
var propertyInfos = GetType().GetProperties().Where(pi => !builtinProperties.Contains(pi.Name));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
var propertyInfo = propertyInfos.Where(pi => pi.Name == reader.Name).FirstOrDefault();
if (propertyInfo != null)
{
reader.ReadStartElement();
var serializer = new XmlSerializer(propertyInfo.PropertyType);
propertyInfo.SetValue(this, serializer.Deserialize(reader));
reader.ReadEndElement();
}
else
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var propertyInfos = GetType().GetProperties()
.Where(pi => pi.CanWrite && !builtinProperties.Contains(pi.Name)).ToList();
foreach (var propertyInfo in propertyInfos)
{
var serializer = new XmlSerializer(propertyInfo.PropertyType);
writer.WriteStartElement(propertyInfo.Name);
serializer.Serialize(writer, propertyInfo.GetValue(this), xmlNamespace);
writer.WriteEndElement();
}
foreach (TKey key in Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key, xmlNamespace);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value, xmlNamespace);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
#region Operators
public static implicit operator SerializableDictionary<TKey, TValue>(Hashtable hashtable)
{
var serializableDictionary = new SerializableDictionary<TKey, TValue>();
foreach (DictionaryEntry item in hashtable)
{
try
{
serializableDictionary.Add((TKey)item.Key, (TValue)item.Value);
}
catch (Exception ex)
{
throw new ArgumentException(string.Format("The entry with the key '{0}' could not be added due to the error: {1}", item.Key, ex.Message), ex);
}
}
return serializableDictionary;
}
public static implicit operator Hashtable(SerializableDictionary<TKey, TValue> serializableDictionary)
{
var hashtable = new Hashtable();
foreach (var item in serializableDictionary)
{
hashtable.Add(item.Key, item.Value);
}
return hashtable;
}
#endregion
}
}
``` | /content/code_sandbox/LabXml/Stores/SerializableDictionary.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 831 |
```smalltalk
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class DictionaryXmlStore<TKey, TValue> : SerializableDictionary<TKey, TValue>
{
public DictionaryXmlStore()
{ }
public DictionaryXmlStore(Hashtable hashtable)
{
foreach (DictionaryEntry kvp in hashtable)
{
Add((TKey)kvp.Key, (TValue)kvp.Value);
}
}
public void Export(string path)
{
File.Delete(path);
var serializer = new XmlSerializer(GetType());
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
FileStream fileStream = new FileStream(path, FileMode.CreateNew);
serializer.Serialize(fileStream, this, xmlNamespace);
fileStream.Close();
}
public string ExportToString()
{
var serializer = new XmlSerializer(GetType());
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
var sb = new StringBuilder();
var sw = new StringWriter(sb);
serializer.Serialize(sw, this, xmlNamespace);
sw.Close();
return sb.ToString();
}
public void ExportToRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(GetType());
var xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
StringWriter sw = new StringWriter();
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(registryPath);
serializer.Serialize(sw, this, xmlNamespace);
key.SetValue(valueName, sw.ToString(), Microsoft.Win32.RegistryValueKind.String);
key.Close();
}
public void AddFromFile(string path)
{
var serializer = new XmlSerializer(typeof(DictionaryXmlStore<TKey, TValue>));
FileStream fileStream = new FileStream(path, FileMode.Open);
var newItems = (DictionaryXmlStore<TKey, TValue>)serializer.Deserialize(fileStream);
newItems.ForEach(item => Add(item.Key, item.Value));
fileStream.Close();
}
public static DictionaryXmlStore<TKey, TValue> Import(string path)
{
var serializer = new XmlSerializer(typeof(DictionaryXmlStore<TKey, TValue>));
FileStream fileStream = new FileStream(path, FileMode.Open);
var items = (DictionaryXmlStore<TKey, TValue>)serializer.Deserialize(fileStream);
fileStream.Close();
return items;
}
public static DictionaryXmlStore<TKey, TValue> ImportFromString(string s)
{
var serializer = new XmlSerializer(typeof(DictionaryXmlStore<TKey, TValue>));
var sr = new StringReader(s);
var items = (DictionaryXmlStore<TKey, TValue>)serializer.Deserialize(sr);
sr.Close();
return items;
}
public static DictionaryXmlStore<TKey, TValue> ImportFromRegistry(string keyName, string valueName)
{
var serializer = new XmlSerializer(typeof(DictionaryXmlStore<TKey, TValue>));
//makes sure the key exists and does nothing if does already exist
var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var registryPath = string.Format(@"SOFTWARE\{0}\{1}", assemblyName, keyName);
var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(registryPath);
if (key == null)
throw new FileNotFoundException(string.Format("The registry key '{0}' does not exist", registryPath));
var value = key.GetValue(valueName);
if (value == null)
throw new FileNotFoundException(string.Format("The registry value '{0}' does not exist in key '{1}'", valueName, registryPath));
StringReader sr = new StringReader(value.ToString());
var items = (DictionaryXmlStore<TKey, TValue>)serializer.Deserialize(sr);
sr.Close();
return items;
}
}
}
``` | /content/code_sandbox/LabXml/Stores/DictionaryXmlStore.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 845 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
namespace AutomatedLab
{
static class Extensions
{
public delegate TOut Action2<TIn, TOut>(TIn element);
public static IEnumerable<TOut> ForEach<TIn, TOut>(this IEnumerable<TIn> source, Action2<TIn, TOut> action)
{
if (source == null) { throw new ArgumentException(); }
if (action == null) { throw new ArgumentException(); }
foreach (TIn element in source)
{
TOut result = action(element);
yield return result;
}
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) { throw new ArgumentException(); }
if (action == null) { throw new ArgumentException(); }
foreach (T element in source)
{
action(element);
}
}
public static void AppendString(this SecureString secureString, string s)
{
foreach (var c in s)
{
secureString.AppendChar(c);
}
}
public static T Copy<T>(this object from) where T : class, new()
{
T to = new T();
var toProperties = to.GetType().GetProperties().Where(p => p.CanWrite).ToList();
var fromProperties = from.GetType().GetProperties();
foreach (var toProperty in toProperties)
{
var fromProperty = fromProperties.Where(p => p.Name == toProperty.Name && p.PropertyType == toProperty.PropertyType).FirstOrDefault();
if (fromProperty != null)
{
toProperty.SetValue(to, fromProperty.GetValue(from));
}
}
return to;
}
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
{
return source.Skip(Math.Max(0, source.Count() - N));
}
public static T TakeLast<T>(this IEnumerable<T> source)
{
return source.Skip(Math.Max(0, source.Count() - 1)).FirstOrDefault();
}
}
}
``` | /content/code_sandbox/LabXml/Extensions/Extensions.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 441 |
```smalltalk
using AutomatedLab;
using LabXml;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
public class ValidatorBase : IValidate
{
protected ValidationMessageContainer messageContainer;
protected static Hashtable validationSettings;
public ValidationMessageContainer MessageContainer
{
get { return messageContainer; }
set { messageContainer = value; }
}
public static Hashtable ValidationSettings
{
get { return validationSettings; }
set { validationSettings = value; }
}
public TimeSpan Runtime
{
get { return messageContainer.Runtime; }
}
public ValidatorBase()
{
messageContainer = new ValidationMessageContainer();
if (validationSettings == null)
{
PowerShellHelper.InvokeCommand("Import-Module -Name AutomatedLab");
validationSettings = (Hashtable)PowerShellHelper.InvokeCommand("[hashtable](Get-LabConfigurationItem -Name ValidationSettings)").FirstOrDefault().BaseObject;
}
}
public ValidationMessageContainer RunValidation()
{
var start = DateTime.Now;
System.Threading.Thread.Sleep(10);
var container = new ValidationMessageContainer();
container.Messages = Validate().ToList();
container.ValidatorName = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().DeclaringType.Name;
var end = DateTime.Now;
container.Runtime = end - start;
return container;
}
public virtual IEnumerable<ValidationMessage> Validate()
{
return new List<ValidationMessage>() { new ValidationMessage() { Message = "Dummy" } };
}
}
}
public interface IValidate
{
IEnumerable<ValidationMessage> Validate();
ValidationMessageContainer MessageContainer { get; }
}
``` | /content/code_sandbox/LabXml/Validator/ValidatorBase.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 355 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace AutomatedLab
{
public class XmlValidator : ValidatorBase
{
protected List<XmlDocument> docs = new List<XmlDocument>();
public XmlValidator(string xmlPath, bool loadAdditionalXmlFiles = true)
{
XmlDocument mainDoc = new XmlDocument();
mainDoc.Load(xmlPath);
docs.Add(mainDoc);
var xmlPaths = mainDoc.SelectNodes("//@Path").OfType<XmlAttribute>().Select(e => e.Value).Where(text => text.EndsWith(".xml"));
foreach (var path in xmlPaths)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
docs.Add(doc);
}
}
public XmlValidator() :
this(XmlValidatorArgs.XmlPath, XmlValidatorArgs.LoadAdditionalFiles)
{ }
}
public static class XmlValidatorArgs
{
public static string XmlPath { get; set; }
public static bool LoadAdditionalFiles { get; set; }
}
}
``` | /content/code_sandbox/LabXml/Validator/XmlValidator.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 211 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AutomatedLab
{
public class LabValidator : ValidatorBase, IValidate
{
private List<XmlDocument> docs = new List<XmlDocument>();
protected Lab lab;
protected ListXmlStore<Machine> machines = new ListXmlStore<Machine>();
public LabValidator(string labXmlPath)
{
XmlDocument mainDoc = new XmlDocument();
mainDoc.Load(labXmlPath);
docs.Add(mainDoc);
var xmlPaths = mainDoc.SelectNodes("//@Path").OfType<XmlAttribute>().Select(e => e.Value).Where(text => text.EndsWith(".xml"));
foreach (var path in xmlPaths)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
docs.Add(doc);
}
lab = Lab.Import(labXmlPath);
lab.MachineDefinitionFiles.ForEach(file => machines.AddFromFile(file.Path));
lab.Machines = machines;
}
public LabValidator() :
this(XmlValidatorArgs.XmlPath)
{ }
}
public static class LabValidatorArgs
{
public static string XmlPath { get; set; }
}
}
``` | /content/code_sandbox/LabXml/Validator/LabValidator.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 255 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace AutomatedLab
{
public class ValidationMessage
{
public MessageType Type { get; set; }
public string Message { get; set; }
public string ValueName { get; set; }
public string TargetObject { get; set; }
public string HelpText { get; set; }
public string ValidatorName { get; set; }
public ValidationMessage()
{
try
{
ValidatorName = new StackTrace().GetFrame(5).GetMethod().DeclaringType.Name;
}
catch
{
ValidatorName = "unknown";
}
}
public override string ToString()
{
return string.Format("{0}: {1}, Target Object {2} from value {3} ", Type, Message, TargetObject, ValueName);
}
}
public class ValidationMessageContainer
{
private string validatorName;
private List<ValidationMessage> messages;
private TimeSpan runtime;
private bool pass;
public string ValidatorName
{
get { return validatorName; }
set { validatorName = value; }
}
public List<ValidationMessage> Messages
{
get { return messages; }
set { messages = value; }
}
public TimeSpan Runtime
{
get { return runtime; }
set { runtime = value; }
}
public bool Pass
{
get
{
if (messages.Where(m => m.Type == MessageType.Error).Count() > 0)
return false;
else
return true;
}
}
public ValidationMessageContainer()
{
messages = new List<ValidationMessage>();
}
public ValidationMessageContainer(string validatorName, TimeSpan runtime, IEnumerable<ValidationMessage> messages)
{
this.validatorName = validatorName;
this.messages = messages.ToList();
this.runtime = runtime;
}
public override string ToString()
{
return string.Format("{0} ({1} Messages)", validatorName, messages.ToString());
}
public void AddSummary()
{
pass = true;
if (messages.Where(m => m.Type == MessageType.Error).Count() > 0)
{
messages.Add(new ValidationMessage
{
Message = "Error",
Type = MessageType.Summary,
TargetObject = "Lab",
ValidatorName = MethodBase.GetCurrentMethod().Name
});
pass = false;
}
else if (messages.Where(m => m.Type == MessageType.Warning).Count() > 0)
{
messages.Add(new ValidationMessage
{
Message = "Warning",
Type = MessageType.Summary,
TargetObject = "Lab",
ValidatorName = MethodBase.GetCurrentMethod().Name
});
}
else
{
messages.Add(new ValidationMessage
{
Message = "Ok",
Type = MessageType.Summary,
TargetObject = "Lab",
ValidatorName = MethodBase.GetCurrentMethod().Name
});
}
}
public IEnumerable<ValidationMessage> GetFilteredMessages(MessageType filter = MessageType.Default)
{
return messages.Where(m => (m.Type & filter) == m.Type);
}
public static ValidationMessageContainer operator +(ValidationMessageContainer source, ValidationMessageContainer destination)
{
destination.messages.AddRange(source.messages);
destination.runtime += source.runtime;
return destination;
}
}
[Flags]
public enum MessageType
{
Debug = 1,
Verbose = 2,
Information = 4,
Warning = 8,
Error = 16,
Summary = 32,
All = Debug | Verbose | Information | Warning | Error | Summary,
Default = Information | Warning | Error | Summary,
VerboseDebug = Verbose | Debug
}
}
``` | /content/code_sandbox/LabXml/Validator/ValidationMessage.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 802 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class RoutingRoleNotSupportedOnAzure : LabValidator, IValidate
{
public RoutingRoleNotSupportedOnAzure()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var role = Roles.Routing;
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.Azure);
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("The role '{0}' is not supported on Azure", role.ToString()),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Routing/RoutingRoleNotSupportedOnAzure.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 207 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class RoutingMachineHasAtLeastTwoNetworkCards : LabValidator, IValidate
{
public RoutingMachineHasAtLeastTwoNetworkCards()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Roles.Where(r =>
r.Name == Roles.Routing).Count() > 0 &
m.HostType == VirtualizationHost.HyperV
& m.NetworkAdapters.Count < 2);
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("The machine '{0}' does not have at least 2 network interfaces for routing", machine.Name),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Routing/RoutingMachineHasAtLeastTwoNetworkCards.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 226 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// Report all disks that are assigned more than once.
/// </summary>
public class DiskAssignedMultipleTimes : LabValidator, IValidate
{
public DiskAssignedMultipleTimes()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machineGroups = lab.Machines.SelectMany(m => m.Disks)
.GroupBy(d => d.Name)
.Where(g => g.Count() > 1);
foreach (var machineGroup in machineGroups)
{
yield return new ValidationMessage
{
Message = "Disk as assigned to two machines",
TargetObject = machineGroup.Key,
Type = MessageType.Error
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Disks/DiskAssignedMultipleTimes.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 175 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator creates an error if a machine's name is longer than 15 characters.
/// </summary>
public class DomainWithTooLongName : LabValidator, IValidate
{
public DomainWithTooLongName()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var domains = lab.Domains.Where(d => d.Name.Split('.')[0].Length > 15);
foreach (var domain in domains)
{
yield return new ValidationMessage()
{
Message = "The domain's name is longer than 15 characters",
TargetObject = domain.Name,
Type = MessageType.Error,
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/DomainWithTooLongName.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 169 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator check if there is only one RootDC / FirstChildDC per domain defined.
/// </summary>
public class DuplicateDomainRoles : LabValidator, IValidate
{
public DuplicateDomainRoles()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var rootDcs = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.RootDC));
var firstChildDcs = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FirstChildDC));
//each domain is a group that is checked for more than one RootDc
foreach (var group in rootDcs.GroupBy(machine => machine.DomainName))
{
if (group.Count() > 1)
{
yield return new ValidationMessage
{
Message = "The role RootDC is assinged more than once for the domain",
TargetObject = group.Key,
Type = MessageType.Error
};
}
}
//check if there are more than one FirstChildDC per domain
var dcGroups = firstChildDcs
.GroupBy(dc => dc.Roles.Where(role => role.Name == Roles.FirstChildDC & !role.Properties.ContainsKey("NewDomain")))
.Where(group => group.Count() > 1);
foreach (var dcGroup in dcGroups)
{
foreach (var dc in dcGroup)
{
yield return new ValidationMessage
{
Message = string.Format("The role FirstChildDC is assinged more than once for child domain '{0}'", dc.Roles.Where(role => role.Name == Roles.FirstChildDC).FirstOrDefault().Properties["NewDomain"]),
TargetObject = dc.Name,
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/DuplicateDomainRoles.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 407 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// Print one error for each machine that is in an undefined domain
/// </summary>
public class MachineInAnUndefinedDomain : LabValidator, IValidate
{
public MachineInAnUndefinedDomain()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(machine => !string.IsNullOrEmpty(machine.DomainName))
.Where(machine => !lab.Domains.Select(domain => domain.Name.ToLower()).Contains(machine.DomainName.ToLower()));
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = "Machine is in a undefined domain",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/MachineInAnUndefinedDomain.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 191 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// The local admin's passwords must match the domain admin's credentials on a machine promoted to a RootDC of FirstChildDC
/// </summary>
public class InvalidDomainCredentials : LabValidator, IValidate
{
public InvalidDomainCredentials()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var rootDcs = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.RootDC) && ! machine.SkipDeployment);
var firstChildDcs = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FirstChildDC) && ! machine.SkipDeployment);
foreach (var dc in rootDcs)
{
var domain = lab.Domains.Where(d => d.Name.ToLower() == dc.DomainName.ToLower()).FirstOrDefault();
if (dc.InstallationUser.Password != domain.Administrator.Password)
{
yield return new ValidationMessage
{
Message = "The domain's admin user's password must be the same like the RootDCs installation user's password",
Type = MessageType.Error,
TargetObject = dc.Name
};
}
}
foreach (var dc in firstChildDcs)
{
var domain = lab.Domains.Where(d => d.Name.ToLower() == dc.DomainName.ToLower()).FirstOrDefault();
if (dc.InstallationUser.Password != domain.Administrator.Password)
{
yield return new ValidationMessage
{
Message = "The domain's admin user's password must be the same like the FirstChildDcs installation user's password",
Type = MessageType.Error,
TargetObject = dc.Name
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/InvalidDomainCredentials.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 383 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// Reports all defined domains which do not have any member machine
/// </summary>
public class EmptyDomains : LabValidator, IValidate
{
public EmptyDomains()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var emptyDomains = lab.Domains
.Select(domain => domain.Name.ToLower())
.Except(machines.Where(m => !string.IsNullOrEmpty(m.DomainName)).Select(machine => machine.DomainName.ToLower()));
foreach (var emptyDomain in emptyDomains)
{
yield return new ValidationMessage
{
Message = "Defined domain does not have any member machines",
Type = MessageType.Warning,
TargetObject = emptyDomain
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/EmptyDomains.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 190 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator informs about all defined domains.
/// </summary>
public class DomainInformation : LabValidator, IValidate
{
public DomainInformation()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var domain in lab.Domains)
{
yield return new ValidationMessage
{
Message = "Domain defined",
Type = MessageType.Information,
TargetObject = domain.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/DomainInformation.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 139 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// Print one error for each machine that is in an undefined domain
/// </summary>
public class DoaminHasNoRootOrFirstChildDC : LabValidator, IValidate
{
public DoaminHasNoRootOrFirstChildDC()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var domain in lab.Domains)
{
var machinesInDomain = lab.Machines
.Where(m => !string.IsNullOrEmpty(m.DomainName))
.Where(machine => machine.DomainName.ToLower() == domain.Name.ToLower());
var dcs = machinesInDomain.Where(machine => machine.Roles.Where(role =>
role.Name == Roles.RootDC ||
role.Name == Roles.FirstChildDC).Count() > 0);
if (dcs.Count() < 1)
{
yield return new ValidationMessage
{
Message = "Domain does not have a RootDC or FirstChildDC. Make sure that all domain contain this role and all machines are in the correct domains.",
Type = MessageType.Error,
TargetObject = domain.Name
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/ActiveDirectory/DoaminHasNoRootOrFirstChildDC.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 273 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AutomatedLab
{
/// <summary>
/// Roles take additional properties in a hashtable. If a propery is specified but no value assigned, somthing is wrong an need to be reported.
/// </summary>
public class HyperVWrongRoleSize : LabValidator, IValidate
{
public HyperVWrongRoleSize()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.HyperV).Count() > 0 && m.HostType == VirtualizationHost.Azure);
// According to path_to_url
var validRoleSizePattern = @"_[DE]\d+(s?)_v3|_F\d+s_v2|_M\d+[mlts]*";
foreach (var machine in machines)
{
var problematicRoleSize = string.Empty;
if (!Regex.IsMatch(lab.AzureSettings.DefaultRoleSize, validRoleSizePattern))
{
problematicRoleSize = lab.AzureSettings.DefaultRoleSize;
}
if (machine.AzureProperties.ContainsKey("RoleSize"))
{
problematicRoleSize = string.Empty;
if (!Regex.IsMatch(machine.AzureProperties["RoleSize"], validRoleSizePattern))
{
problematicRoleSize = machine.AzureProperties["RoleSize"];
}
}
if (problematicRoleSize.Equals(string.Empty)) continue;
var msg = "The role size '{0}' defined for machine '{1}' or the entire lab is too small for nested virtualization.\r\n" +
"Choose any role size that matches {2} as outlined on path_to_url";
yield return new ValidationMessage
{
Message = string.Format(msg, problematicRoleSize, machine.Name, validRoleSizePattern),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/HyperV/HyperVWrongRoleSize.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 424 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// Roles take additional properties in a hashtable. If a propery is specified but no value assigned, somthing is wrong an need to be reported.
/// </summary>
public class HyperVWrongOs : LabValidator, IValidate
{
public HyperVWrongOs()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.HyperV).Count() > 0 && m.OperatingSystem.Version < new Version(10, 0));
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("OS version {0} of VM {1} is too low to enable nested virtualization.", machine.OperatingSystem.Version.ToString(), machine.Name),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/HyperV/HyperVWrongOs.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 222 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator informs about all defined machines.
/// </summary>
public class MachineInformation : LabValidator, IValidate
{
public MachineInformation()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var machine in machines)
{
yield return new ValidationMessage()
{
Message = "Machine defined in lab",
TargetObject = machine.Name,
Type = MessageType.Information,
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/MachineInformation.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 139 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator informs about all roles defined in the lab.
/// </summary>
public class MachineRoleInformation : LabValidator, IValidate
{
public MachineRoleInformation()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (Roles role in Enum.GetValues(typeof(AutomatedLab.Roles)))
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
foreach (var machine in machines)
{
yield return new ValidationMessage()
{
Message = "Role defined",
TargetObject = role.ToString(),
ValueName = machine.Name,
Type = MessageType.Information
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/MachineRoleInformation.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 198 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator creates an error if a machine's name is longer than 15 characters.
/// </summary>
public class MachineWithTooLongName : LabValidator, IValidate
{
public MachineWithTooLongName()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Name.Length > 15);
foreach (var machine in machines)
{
yield return new ValidationMessage()
{
Message = "The machine's name is longer than 15 characters",
TargetObject = machine.Name,
Type = MessageType.Error,
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/MachineWithTooLongName.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 165 |
```smalltalk
using System.Collections.Generic;
namespace AutomatedLab
{
/// <summary>
/// This validator creates an error if no machine is defined in the lab.
/// </summary>
public class NoMachinesDefined : LabValidator, IValidate
{
public NoMachinesDefined()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
if (machines.Count == 0)
{
yield return new ValidationMessage()
{
Message = "There are no machines defined in the lab",
TargetObject = lab.Name,
Type = MessageType.Error,
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/NoMachinesDefined.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 139 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for duplicate machine names inside a lab.
/// </summary>
public class DuplicateMachineNames : LabValidator, IValidate
{
public DuplicateMachineNames()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var duplicateMachineGroups = machines.GroupBy(machine => machine.Name)
.Where(group => group.Count() > 1);
foreach (var duplicateMachineGroup in duplicateMachineGroups)
{
yield return new ValidationMessage()
{
Message = "Duplicate Computer name defined",
Type = MessageType.Error,
TargetObject = duplicateMachineGroup.Key
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/DuplicateMachineNames.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 164 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for Hyper-V machine that have more than 8 network adapters and reports errors.
/// </summary>
public class HypervDoesSupportMax8NetworkAdapters : LabValidator, IValidate
{
public HypervDoesSupportMax8NetworkAdapters()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var machine in machines.Where(m=>m.HostType == VirtualizationHost.HyperV && m.NetworkAdapters.Count > 8))
{
yield return new ValidationMessage()
{
Message = "Hyper-V does not support machines with more than 8 network adapters",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/HyperV/HypervDoesSupportMax8NetworkAdapters.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 183 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for duplicate machine names inside a lab.
/// </summary>
public class HyperVAdminHasMachineName : LabValidator, IValidate
{
public HyperVAdminHasMachineName()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var adminUserNotPossible = machines.Where(mach => mach.HostType.Equals(VirtualizationHost.HyperV) && mach.InstallationUser.UserName.Equals(mach.Name, System.StringComparison.InvariantCultureIgnoreCase));
foreach (var impossibleUser in adminUserNotPossible)
{
yield return new ValidationMessage()
{
Message = $"Admin user name {impossibleUser.InstallationUser.UserName} may not be machine name {impossibleUser.Name}",
Type = MessageType.Error,
TargetObject = impossibleUser.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/HyperV/HyperVAdminHasMachineName.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 204 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for Hyper-V machine that have more than 8 network adapters and reports errors.
/// </summary>
public class HypervMemorySettings : LabValidator, IValidate
{
public HypervMemorySettings()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var machine in machines.Where(m => m.HostType == VirtualizationHost.HyperV))
{
if (
(machine.MaxMemory != 0 & machine.MinMemory == 0) |
(machine.MaxMemory == 0 & machine.MinMemory != 0)
)
yield return new ValidationMessage()
{
Message = "If MaxMemory is defined MinMemory has to be defined as well and vice versa.",
Type = MessageType.Error,
TargetObject = machine.Name
};
if (machine.MinMemory != 0 && (machine.MinMemory > machine.Memory) | (machine.MinMemory > machine.MaxMemory))
yield return new ValidationMessage()
{
Message = "MinMemory is larger than MaxMemory or Memory",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/HyperV/HypervMemorySettings.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 271 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for non-supported combos of OS and VM Generation.
/// </summary>
public class AzureVmGenerationDoesNotFitSku : LabValidator, IValidate
{
public AzureVmGenerationDoesNotFitSku()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
if (lab.AzureSettings == null)
yield break;
var azVms = machines.Where(machine => machine.HostType == VirtualizationHost.Azure);
foreach (var machine in azVms)
{
var azImg = lab.AzureSettings.VmImages.Where(s => s.AutomatedLabOperatingSystemName == machine.OperatingSystem.OperatingSystemName && s.HyperVGeneration.ToLower() == $"v{machine.VmGeneration}");
if (azImg.Count() > 0) continue;
yield return new ValidationMessage()
{
Message = string.Format("VM {0} is of generation {1}, but no OS was found that matches {2} and generation {1}", machine.Name, machine.VmGeneration, machine.OperatingSystem.OperatingSystemName),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/Azure/AzureVmGenerationDoesNotFitSku.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 278 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for Azure machine that have more than 4 network adapters and reports errors.
/// </summary>
public class AzureDoesSupportMax4NetworkAdapters : LabValidator, IValidate
{
public AzureDoesSupportMax4NetworkAdapters()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
foreach (var machine in machines.Where(m=>m.HostType == VirtualizationHost.Azure && m.NetworkAdapters.Count > 4))
{
yield return new ValidationMessage()
{
Message = "Azure does not support machines with more than 8 network adapters",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/Azure/AzureDoesSupportMax8NetworkAdapters.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 177 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required OS Versions are used
/// </summary>
public class DynamicsMinOsVersion : LabValidator, IValidate
{
public DynamicsMinOsVersion()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.DynamicsAdmin || r.Name == Roles.DynamicsBackend || r.Name == Roles.DynamicsFrontend || r.Name == Roles.DynamicsFull).Count() > 0 && m.OperatingSystem.Version < new Version(10, 0));
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("OS version {0} too low, required >=10.0", machine.OperatingSystem.Version.ToString()),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Dynamics/DynamicsMinOsVersion.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 228 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator looks for duplicate machine names inside a lab.
/// </summary>
public class AzureSpecifiedRoleSizeNotFound : LabValidator, IValidate
{
public AzureSpecifiedRoleSizeNotFound()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
if (lab.AzureSettings == null)
yield break;
var roleSizeLables = lab.AzureSettings.RoleSizes.Select(r => r.Name);
var machinesWithUnknownRoleSizes = machines
.Where(machine => machine.HostType == VirtualizationHost.Azure && machine.AzureProperties.ContainsKey("RoleSize"))
.Where(machine => !roleSizeLables.Contains(machine.AzureProperties["RoleSize"]));
foreach (var machine in machinesWithUnknownRoleSizes)
{
yield return new ValidationMessage()
{
Message = string.Format("The specified role {0} does not exist in Azure. Please run '(Get-LabDefinition).AzureSettings.RoleSizes' to get a list of available role sizes.", machine.AzureProperties["RoleSize"]),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Machines/Azure/AzureSpecifiedRoleSizeNotFound.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 262 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required SQL Versions are present
/// Dynamics 365: SQL 2016+
/// </summary>
public class DynamicsCorrectSql : LabValidator, IValidate
{
public DynamicsCorrectSql()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var DynamicsRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Dynamics"));
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("SQLServer"));
var sqlvms = new List<Machine>();
foreach (var role in sqlRoles)
{
lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0).ForEach(m => sqlvms.Add(m));
}
foreach (var role in DynamicsRoles)
{
var Dynamicsvms = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
foreach (var vm in Dynamicsvms)
{
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.DynamicsFull | r.Name == Roles.DynamicsAdmin | r.Name == Roles.DynamicsBackend | r.Name == Roles.DynamicsFrontend) != null && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2017) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("Dynamics 365 on {0} requires SQL 2016 or newer", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Dynamics/DynamicsCorrectSql.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 407 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// There can only be one Azure DevOps role!
/// Unless the machine is an actual machine that uses Azure DevOps Server
/// </summary>
public class HighlanderRole : LabValidator, IValidate
{
public HighlanderRole()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var devopsRole = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).First(r => r.ToString() == "AzDevOps");
var machines = lab.Machines.Where(m => m.Roles.Count > 1 && m.Roles.Where(r => r.Name == devopsRole).Count() > 0 && m.SkipDeployment);
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("Machine {0} is using Azure DevOps (dev.azure.com) but has other roles assigned.", machine.ToString()),
Type = MessageType.Error,
TargetObject = machine.ToString()
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Tfs/HighlanderRole.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 255 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class TfsIsosExist : LabValidator, IValidate
{
public TfsIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var devopsRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => Regex.IsMatch(r.ToString(), @"Tfs\d{4}|AzDevOps"));
foreach (var role in devopsRoles)
{
// SkipDeployment: It is an Azure DevOps hosted instance somewhere
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 && !m.SkipDeployment);
if (machines.Count() > 0 && lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Tfs/TfsIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 289 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class OfficeIsosExist : LabValidator, IValidate
{
public OfficeIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Office"));
foreach (var role in sqlRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Office/OfficeIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 263 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class ScvmmIsosExist : LabValidator, IValidate
{
public ScvmmIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Scvmm"));
foreach (var role in sqlRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCVMM/ScvmmIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 269 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// Azure DevOps Server 2019 Azure SQL Database, SQL Server 2017, SQL Server 2019, SQL Server 2016 (minimum SP1)
/// TFS 2018 SQL Server 2017
/// SQL Server 2016 (minimum SP1)
/// TFS 2017 Update 1 SQL Server 2016 (minimum SP1)
/// SQL Server 2014
/// TFS 2017 SQL Server 2016
/// SQL Server 2014
/// TFS 2015 Update 3 SQL Server 2016
/// SQL Server 2014
/// SQL Server 2012 (minimum SP1)
/// TFS 2015 SQL Server 2014
/// SQL Server 2012 (minimum SP1)
/// </summary>
public class TfsSqlIsosExist : LabValidator, IValidate
{
public TfsSqlIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var devopsRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => Regex.IsMatch(r.ToString(), @"Tfs\d{4}|AzDevOps"));
foreach (var role in devopsRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 && !m.SkipDeployment);
if (machines.Count() == 0) continue;
List<string> sqlmachines = new List<string>();
List<string> requiredRoles = new List<string>();
switch (role)
{
case Roles.Tfs2015:
requiredRoles.Add("2014");
sqlmachines.AddRange(lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.SQLServer2014).Count() > 0).Select(m => m.Name));
break;
case Roles.Tfs2017:
requiredRoles.Add("2014");
requiredRoles.Add("2016");
sqlmachines.AddRange(lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.SQLServer2014 || r.Name == Roles.SQLServer2016).Count() > 0).Select(m => m.Name));
break;
case Roles.Tfs2018:
requiredRoles.Add("2017");
sqlmachines.AddRange(lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.SQLServer2017).Count() > 0).Select(m => m.Name));
break;
case Roles.AzDevOps:
requiredRoles.Add("2017");
requiredRoles.Add("2019");
sqlmachines.AddRange(lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2019).Count() > 0).Select(m => m.Name));
break;
default:
break;
}
if (sqlmachines.Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no fitting SQL server for TFS/DevOps server role '{0}' defined. {0} requires SQL roles {1}", role.ToString(), string.Join(",", requiredRoles.ToArray())),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Tfs/TfsSqlIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 771 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required SQL Versions are present
/// SCVMM 2019: SQL 2016, SQL 2017 (not SQL 2019)
/// SCVMM 2016: SQL 2012, SQL 2014, SQL 2016
/// </summary>
public class ScvmmCorrectSql : LabValidator, IValidate
{
public ScvmmCorrectSql()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var scvmmRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Scvmm"));
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("SQLServer"));
var sqlvms = new List<Machine>();
foreach (var role in sqlRoles)
{
lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0).ForEach(m => sqlvms.Add(m));
}
foreach (var role in scvmmRoles)
{
var scvmmvms = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
foreach (var vm in scvmmvms.Where(m => ! m.Roles.FirstOrDefault(r => r.Name == role).Properties.ContainsKey("SkipServer")))
{
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2016) != null && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2012 || r.Name == Roles.SQLServer2014 || r.Name == Roles.SQLServer2016) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM Server 2016 requires SQL 2012, 2014 or 2016", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2019) != null && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2017) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM Server 2019 requires SQL 2016 or 2017", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2022) != null && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2019 || r.Name == Roles.SQLServer2022) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM Server 2022 requires SQL 2017 or 2019 or 2022", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCVMM/ScvmmCorrectSql.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 707 |
```smalltalk
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// Roles take additional properties in a hashtable. If a propery is specified but no value assigned, somthing is wrong an need to be reported.
/// </summary>
public class UnknownRoleProperties : LabValidator, IValidate
{
public UnknownRoleProperties()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var validRoleProperties = (Hashtable)validationSettings["ValidRoleProperties"];
var machinesWithRoles = machines.Where(machine => machine.Roles.Count > 0);
foreach (var machine in machinesWithRoles)
{
foreach (var role in machine.Roles.Where(r => validRoleProperties.ContainsKey(r.Name.ToString())))
{
var validKeys = new List<string>();
var keysFromModule = ((object[])validRoleProperties[role.Name.ToString()]).Cast<string>().ToArray();
if (keysFromModule.GetType().IsArray)
validKeys.AddRange(keysFromModule);
else
{
validKeys.Add(keysFromModule.FirstOrDefault());
}
var unknownProperties = role.Properties.Keys.Where(k => !validKeys.Contains(k));
var validKeysString = validKeys.Aggregate(
new System.Text.StringBuilder(),
(current, next) => current.Append(current.Length == 0 ? "" : ", ").Append(next))
.ToString();
foreach (var unknownProperty in unknownProperties)
{
yield return new ValidationMessage
{
Message = string.Format("The property '{0}' is unknown for role '{1}'. Please use one of the following properties: {2}",
unknownProperty, role.Name, validKeysString),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Roles/UnknownRoleProperties.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 385 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required SQL Versions are present
/// SCVMM 2019: SQL 2016, SQL 2017 (not SQL 2019)
/// SCVMM 2016: SQL 2012, SQL 2014, SQL 2016
/// </summary>
public class ScvmmMinOsVersion : LabValidator, IValidate
{
public ScvmmMinOsVersion()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var scvmmRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Scvmm"));
foreach (var role in scvmmRoles)
{
var scvmmServers = new List<Machine>();
var scvmmConsoles = new List<Machine>();
lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 && !m.Roles.FirstOrDefault(r => r.Name == role).Properties.ContainsKey("SkipServer")).ForEach(m => scvmmServers.Add(m));
lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 && m.Roles.FirstOrDefault(r => r.Name == role).Properties.ContainsKey("SkipServer")).ForEach(m => scvmmConsoles.Add(m));
foreach (var vm in scvmmServers)
{
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2016 || r.Name == Roles.Scvmm2019) != null && vm.OperatingSystem.Version < new Version(10, 0))
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM 2016/2019 requires at least Windows Server 2016", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
}
foreach (var vm in scvmmConsoles)
{
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2016) != null && vm.OperatingSystem.Version < new Version(6, 2))
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM 2016 Console requires at least Windows Server 2012", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (vm.Roles.FirstOrDefault(r => r.Name == Roles.Scvmm2019) != null && vm.OperatingSystem.Version < new Version(10, 0))
{
yield return new ValidationMessage
{
Message = string.Format("SCVMM 2019 Console requires Windows Server 2016 or 2019", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCVMM/ScvmmMinOsVersion.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 628 |
```smalltalk
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace AutomatedLab
{
/// <summary>
/// Roles take additional properties in a hashtable. If a propery is specified but no value assigned, somthing is wrong an need to be reported.
/// </summary>
public class MandatoryRoleProperties : LabValidator, IValidate
{
public MandatoryRoleProperties()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
Hashtable mandatoryRoleProperties = (Hashtable)validationSettings["MandatoryRoleProperties"];
var machinesWithRoles = machines.Where(machine => machine.Roles.Count > 0);
foreach (var machine in machinesWithRoles)
{
foreach (var role in machine.Roles.Where(r => mandatoryRoleProperties.ContainsKey(r.Name.ToString())))
{
var mandatoryKeys = new List<string>();
//var keysFromModule = mandatoryRoleProperties[role.Name.ToString()];
var keysFromModule = ((object[])((PSObject)mandatoryRoleProperties[role.Name.ToString()]).BaseObject).Cast<string>().ToArray();
if (keysFromModule.GetType().IsArray)
mandatoryKeys.AddRange(keysFromModule);
else
mandatoryKeys.Add(keysFromModule.FirstOrDefault());
foreach (string mandatoryRoleProperty in mandatoryKeys)
{
if (!role.Properties.ContainsKey(mandatoryRoleProperty) || string.IsNullOrEmpty(role.Properties[mandatoryRoleProperty]))
{
yield return new ValidationMessage
{
Message = string.Format("The property '{0}' is required for role '{1}'", mandatoryRoleProperty, role.Name),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Roles/MandatoryRoleProperties.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 359 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.FailoverCluster
{
class DscSqlServerKnown : LabValidator, IValidate
{
public DscSqlServerKnown()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var role = Roles.DSCPullServer;
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
foreach (var machine in machines)
{
var dscRole = machine.Roles.Where(r => r.Name == role).FirstOrDefault();
if (dscRole.Properties.ContainsKey("DatabaseEngine") && dscRole.Properties["DatabaseEngine"].ToLower() == "sql")
{
if (!dscRole.Properties.ContainsKey("SqlServer"))
{
yield return new ValidationMessage
{
Message = "The database engine for the DSC Pull Server role is 'sql' but there is no 'SqlServer' defined",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
if (!dscRole.Properties.ContainsKey("DatabaseName"))
{
yield return new ValidationMessage
{
Message = "The database engine for the DSC Pull Server role is 'sql' but there is no 'DatabaseName' defined",
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/DscPullServer/DscSqlServerKnown.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 313 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// Roles take additional properties in a hashtable. If a propery is specified but no value assigned, somthing is wrong an need to be reported.
/// </summary>
public class EmptyRoleProperties : LabValidator, IValidate
{
public EmptyRoleProperties()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machinesWithRoles = machines.Where(machine => machine.Roles.Count > 0);
foreach (var machine in machinesWithRoles)
{
foreach (var role in machine.Roles)
{
var properties = role.Properties.Where(p => string.IsNullOrEmpty(p.Value));
foreach (var property in properties)
{
yield return new ValidationMessage
{
Message = string.Format("The property '{0}' defined in role '{1}' is empty", property, role.Name),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Roles/EmptyRoleProperties.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 224 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class VisualStudioIsosExist : LabValidator, IValidate
{
public VisualStudioIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("VisualStudio"));
foreach (var role in sqlRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/VisualStudio/VisualStudioIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 266 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.FailoverCluster
{
class DscSqlServerPresent : LabValidator, IValidate
{
public DscSqlServerPresent()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var role = Roles.DSCPullServer;
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
var sqlServers = lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2019).Count() > 0);
foreach (var machine in machines)
{
var dscRole = machine.Roles.Where(r => r.Name == role).FirstOrDefault();
if (dscRole.Properties.ContainsKey("DatabaseEngine") && dscRole.Properties["DatabaseEngine"].ToLower() == "sql")
{
if (dscRole.Properties.ContainsKey("SqlServer"))
{
var targetedSqlServer = dscRole.Properties["SqlServer"];
if (sqlServers.Where(m => m.Name == targetedSqlServer).Count() < 1)
{
yield return new ValidationMessage
{
Message = string.Format("The database server for the DSC Pull Server role is '{0}' but there is no SQL Server 2016 or 2017 defined inthe lab with that name", targetedSqlServer),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/DscPullServer/DscSqlServerPresent.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 347 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.FailoverCluster
{
class ClusterNoDomain : LabValidator, IValidate
{
public ClusterNoDomain()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var failoverNodes = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverNode));
Dictionary<string, List<Machine>> clusters = new Dictionary<string, List<Machine>>();
foreach (var node in failoverNodes)
{
var tempNode = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First();
var clusterName = "ALCluster";
if (tempNode.Properties.ContainsKey("ClusterName"))
{
clusterName = tempNode.Properties["ClusterName"].ToString();
}
if (!clusters.ContainsKey(clusterName))
{
clusters.Add(clusterName, new List<Machine>());
}
clusters[clusterName].Add(node);
}
foreach (var cluster in clusters)
{
var domainCount = cluster.Value.Where(machine => !string.IsNullOrWhiteSpace(machine.DomainName)).Select(machine => machine.DomainName).Distinct().Count();
if (domainCount == 1)
{
continue;
}
var clusterFail = false;
foreach (var node in cluster.Value)
{
if (node.OperatingSystem.Version >= new Version { Major = 10 })
{
continue;
}
clusterFail = true;
}
if (clusterFail)
{
yield return new ValidationMessage
{
Message = "Workgroup or multidomain clusters are only supported starting with Server 2016",
TargetObject = cluster.Key,
Type = MessageType.Error
};
}
else
{
yield return new ValidationMessage
{
Message = "Workgroup or multidomain clusters supported with Server 2016",
TargetObject = cluster.Key,
Type = MessageType.Information
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/FailoverCluster/ClusterNoDomain.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 433 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class SqlIsosExist : LabValidator, IValidate
{
public SqlIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("SQLServer"));
foreach (var role in sqlRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV && ! m.SkipDeployment);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SQL/SqlIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 269 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator informs about all defined domains.
/// </summary>
public class TooFewNodesForCluster : LabValidator, IValidate
{
public TooFewNodesForCluster()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var failoverNodes = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverNode));
Dictionary<string, List<Machine>> clusters = new Dictionary<string, List<Machine>>();
foreach (var node in failoverNodes)
{
var tempNode = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First();
var clusterName = "ALCluster";
if (tempNode.Properties.ContainsKey("ClusterName"))
{
clusterName = tempNode.Properties["ClusterName"].ToString();
}
if (!clusters.ContainsKey(clusterName))
{
clusters.Add(clusterName, new List<Machine>());
}
clusters[clusterName].Add(node);
}
foreach (var cluster in clusters)
{
if (cluster.Value.Count < 2)
{
yield return new ValidationMessage
{
Message = $"Too few nodes {cluster.Value.Count} for cluster {cluster.Key}",
TargetObject = cluster.Key,
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/FailoverCluster/TooFewNodesForCluster.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 314 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.FailoverCluster
{
class ClusterOperatingSystem : LabValidator, IValidate
{
public ClusterOperatingSystem()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var failoverNodes = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverNode));
if (null != failoverNodes)
{
var oldOs = failoverNodes.Where(machine => machine.OperatingSystem.Version < new Version { Major = 6, Minor = 1 });
if (oldOs.Count() != 0)
{
yield return new ValidationMessage
{
Message = "Failover clustering only works with 2008 R2 or greater",
TargetObject = string.Join(", ", from item in oldOs select item.Name),
Type = MessageType.Error
};
}
}
var storageNodes = machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverStorage));
if (null != storageNodes)
{
var oldOs = storageNodes.Where(machine => machine.OperatingSystem.Version < new Version { Major = 6, Minor = 2 });
if (oldOs.Count() != 0)
{
yield return new ValidationMessage
{
Message = "Failover iSCSI storage only works with 2012 or greater",
TargetObject = string.Join(", ", from item in oldOs select item.Name),
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/FailoverCluster/ClusterOperatingSystem.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 347 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.FailoverCluster
{
class DuplicateClusterIp : LabValidator, IValidate
{
public DuplicateClusterIp()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var clusterToIp = new Dictionary<string, string>();
foreach (var node in machines.Where(machine => machine.Roles.Select(role => role.Name).Contains(Roles.FailoverNode)))
{
var tempNode = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First();
var clusterName = "ALCluster";
if (tempNode.Properties.ContainsKey("ClusterName"))
{
clusterName = tempNode.Properties["ClusterName"].ToString();
}
var clusterIp = "autogenerated";
if (tempNode.Properties.ContainsKey("ClusterIp"))
{
clusterIp = node.Roles.Where(r => r.Name.Equals(Roles.FailoverNode)).First().Properties["ClusterIp"].ToString();
}
if (!clusterToIp.ContainsKey(clusterName))
{
clusterToIp.Add(clusterName, clusterIp);
}
clusterToIp[clusterName] = clusterIp;
}
foreach (var entry in clusterToIp)
{
foreach (var compareTo in clusterToIp)
{
if (entry.Key.Equals(compareTo.Key)) continue;
if (!entry.Value.Equals(compareTo.Value)) continue;
yield return new ValidationMessage
{
Message = $"Duplicate cluster IP {entry.Value} found",
TargetObject = string.Join(", ", new List<string> { entry.Key, compareTo.Key }),
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/FailoverCluster/DuplicateClusterIp.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 365 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// This validator creates an error if a machine's name is longer than 15 characters.
/// </summary>
public class LabNameContainsIllegalCharacters : LabValidator, IValidate
{
public LabNameContainsIllegalCharacters()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var pattern = "^([A-Za-z0-9])+$";
var azurePattern = "^([A-Za-z0-9-_.])+(?<!\\.)$";
if (lab.DefaultVirtualizationEngine.Equals("Azure") && !System.Text.RegularExpressions.Regex.IsMatch(lab.Name, azurePattern))
{
yield return new ValidationMessage()
{
Message = $"The lab name contains invalid characters. Only names matching {azurePattern} are allowed.",
TargetObject = lab.Name,
Type = MessageType.Error,
};
}
if (!System.Text.RegularExpressions.Regex.IsMatch(lab.Name, pattern) && !lab.DefaultVirtualizationEngine.Equals("Azure"))
{
yield return new ValidationMessage()
{
Message = $"The lab name contains invalid characters. Only A-Z, a-z and 0-9 are allowed.",
TargetObject = lab.Name,
Type = MessageType.Error,
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/LabInformation/LabNameContainsIllegalCharacters.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 290 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required OS Versions are used
/// </summary>
public class ScomMinOsVersion : LabValidator, IValidate
{
public ScomMinOsVersion()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == Roles.ScomConsole || r.Name == Roles.ScomManagement || r.Name == Roles.ScomReporting || r.Name == Roles.ScomWebConsole).Count() > 0 && m.OperatingSystem.Version < new Version(10, 0));
foreach (var machine in machines)
{
yield return new ValidationMessage
{
Message = string.Format("OS version {0} too low, required >=10.0", machine.OperatingSystem.Version.ToString()),
Type = MessageType.Error,
TargetObject = machine.Name
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCOM/ScomMinOsVersion.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 230 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required SQL Versions are present
/// Scom 2022: SQL 2017, SQL 2019, SQL 2022
/// Scom 2019: SQL 2016, SQL 2017, SQL 2019
/// Scom 2016: SQL 2012, SQL 2014, SQL 2016
/// </summary>
public class ScomCorrectSql : LabValidator, IValidate
{
public ScomCorrectSql()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var scomRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().Equals("ScomManagement") || r.ToString().Equals("ScomReporting"));
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("SQLServer"));
var sqlvms = new List<Machine>();
foreach (var role in sqlRoles)
{
lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0).ForEach(m => sqlvms.Add(m));
}
foreach (var role in scomRoles)
{
var scomvms = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0);
if (scomvms.Count() == 0) continue;
var iso = lab.Sources.ISOs.First(isoSource => isoSource.Name.StartsWith("Scom"));
foreach (var vm in scomvms.Where(m => ! m.Roles.FirstOrDefault(r => r.Name == role).Properties.ContainsKey("SkipServer")))
{
if (Regex.IsMatch(System.IO.Path.GetFileNameWithoutExtension(iso.Path), "_2016_") && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2012 || r.Name == Roles.SQLServer2014 || r.Name == Roles.SQLServer2016) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("Scom 2016 requires SQL 2012, 2014 or 2016", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (Regex.IsMatch(System.IO.Path.GetFileNameWithoutExtension(iso.Path), "_2019_") && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2019) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("Scom 2016 requires SQL 2016, 2017 or 2019", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (Regex.IsMatch(System.IO.Path.GetFileNameWithoutExtension(iso.Path), "_2022_") && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2019 || r.Name == Roles.SQLServer2022) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("Scom 2022 requires SQL 2017, 2019 or 2022", vm.ToString()),
Type = MessageType.Error,
TargetObject = vm.ToString()
};
}
if (!Regex.IsMatch(System.IO.Path.GetFileNameWithoutExtension(iso.Path), "_2016_|_2019_|_2022_") && sqlvms.Where(m => m.Roles.FirstOrDefault(r => r.Name == Roles.SQLServer2012 || r.Name == Roles.SQLServer2014 || r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2016 || r.Name == Roles.SQLServer2017 || r.Name == Roles.SQLServer2022) != null).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("Unknown Scom Version, ensure that your SQL version is actually supported.", vm.ToString()),
Type = MessageType.Warning,
TargetObject = vm.ToString()
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCOM/ScomCorrectSql.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 935 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class ScomIsosExist : LabValidator, IValidate
{
public ScomIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var scomRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Scom"));
foreach (var role in scomRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == "ScomManagement").Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for 'ScomManagement' defined. Regardless of the SCOM component, please add the ISO with the name ScomManagement"),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/SCOM/ScomIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 287 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
namespace AutomatedLab
{
public class PathValidator : XmlValidator, IValidate
{
public PathValidator()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var pathsNotFound = new List<string>();
foreach (var doc in docs)
{
var paths = doc.SelectNodes("//Path").OfType<XmlElement>().Select(e => e.InnerText);
foreach (var path in paths)
{
if (path.StartsWith("http"))
{
yield return new ValidationMessage()
{
Message = "URI skipped",
TargetObject = path,
Type = MessageType.Verbose
};
continue;
}
if (!File.Exists(path) & !Directory.Exists(path))
{
yield return new ValidationMessage()
{
Message = "The path could not be found",
TargetObject = path,
Type = MessageType.Error
};
}
else
{
yield return new ValidationMessage()
{
Message = "Path verified successfully",
TargetObject = path,
Type = MessageType.Verbose
};
}
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Xml/PathValidator.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 259 |
```smalltalk
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// This validator makes sure the required ISOs are present
/// </summary>
public class OrchestratorIsosExist : LabValidator, IValidate
{
public OrchestratorIsosExist()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var sqlRoles = ((Roles[])Enum.GetValues(typeof(AutomatedLab.Roles))).Where(r => r.ToString().StartsWith("Orchestrator"));
foreach (var role in sqlRoles)
{
var machines = lab.Machines.Where(m => m.Roles.Where(r => r.Name == role).Count() > 0 & m.HostType == VirtualizationHost.HyperV);
if (machines.Count() > 0 & lab.Sources.ISOs.Where(iso => iso.Name == role.ToString()).Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("There is no ISO image for '{0}' defined", role.ToString()),
Type = MessageType.Error,
TargetObject = role.ToString()
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Orchestrator/OrchestratorIsosExist.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 270 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// Validator checks if domain members point to a domain DNS inside the lab
/// Domain Controllers point to themselves and to a second Domain Controller
/// </summary>
public class DomainMemberDns : LabValidator, IValidate
{
public DomainMemberDns()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var domainControllers = lab.Machines
.Where(m => m.Roles.Select(r => r.Name).Where(r => (AutomatedLab.Roles.ADDS & r) == r).Count() > 0);
foreach (var domainController in domainControllers)
{
var dcDns = domainController.NetworkAdapters
.SelectMany(n => n.Ipv4DnsServers);
if (!dcDns.First().AddressAsString.Equals(domainController.IpV4Address))
{
yield return new ValidationMessage
{
Message = string.Format("First DNS server {0} of domain controller {1} points to a different IP {2}", domainController.IpV4Address, domainController.Name, dcDns.First().AddressAsString),
TargetObject = domainController.IpV4Address,
Type = MessageType.Error
};
}
}
foreach (var machine in lab.Machines.Where(m => !string.IsNullOrWhiteSpace(m.DomainName) && m.Roles.Select(r => r.Name).Where(r => (AutomatedLab.Roles.ADDS & r) == r).Count() == 0))
{
var domainDns = domainControllers.Where(dc => dc.DomainName.Equals(machine.DomainName)).Select(dc => dc.IpV4Address);
var machineDns = machine.NetworkAdapters.SelectMany(n => n.Ipv4DnsServers).Where(dns => domainDns.Contains(dns.AddressAsString));
if (machineDns.Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("DNS servers of {0} do not point to any of the domain controllers in it's domain", machine.Name),
TargetObject = machine.Name,
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/DomainMemberDns.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 475 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class DuplicateAddressAssigned : LabValidator, IValidate
{
public DuplicateAddressAssigned()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var dupliateAddresses = lab.Machines.SelectMany(m => m.NetworkAdapters)
.SelectMany(n => n.Ipv4Address)
.GroupBy(ip => ip.IpAddress)
.Where(group => group.Count() > 1);
if (dupliateAddresses.Count() == 0)
yield break;
foreach (var dupliateAddress in dupliateAddresses)
{
yield return new ValidationMessage
{
Message = string.Format("The IP address {0} is assigned multiple times", dupliateAddress.Key),
TargetObject = dupliateAddress.ToList().Select(ip => ip.IpAddress.AddressAsString)
.Aggregate((a, b) => a + ", " + b),
Type = MessageType.Error
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/DuplicateAddressAssigned.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 260 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class NonExistingDnsServerAssigned : LabValidator, IValidate
{
public NonExistingDnsServerAssigned()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var dnsServers = lab.Machines
.Where(m => m.Roles.Select(r => r.Name).Where(r => (AutomatedLab.Roles.ADDS & r) == r).Count() > 0)
.SelectMany(m =>m.NetworkAdapters)
.SelectMany(n => n.Ipv4DnsServers);
var nonExistingDnssServers = lab.Machines
.SelectMany(m => m.NetworkAdapters)
.SelectMany(n => n.Ipv4DnsServers)
.Where(dns => !dnsServers.Contains(dns));
if (nonExistingDnssServers.Count() == 0 | dnsServers.Count() == 0)
yield break;
foreach (var nonExistingDnssServer in nonExistingDnssServers)
{
yield return new ValidationMessage
{
Message = string.Format("The DNS server client address {0} does not point to a valid DNS server in the lab", nonExistingDnssServer.AddressAsString),
TargetObject = nonExistingDnssServer.AddressAsString,
Type = MessageType.Error
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/NonExistingDnsServerAssigned.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 335 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class DuplicateAddressSpaceAssigned : LabValidator, IValidate
{
public DuplicateAddressSpaceAssigned()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var dupliateAddressSpaces = lab.VirtualNetworks.GroupBy(adapter => adapter.AddressSpace).Where(group => group.Count() > 1);
if (dupliateAddressSpaces.Count() == 0)
yield break;
foreach (var dupliateAddressSpace in dupliateAddressSpaces)
{
yield return new ValidationMessage
{
Message = string.Format("The address space {0} is assigned multiple times", dupliateAddressSpace.Key),
TargetObject = dupliateAddressSpace.ToList().Select(vnet => vnet.Name).Aggregate((a, b) => a + ", " + b),
Type = MessageType.Error
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/DuplicateAddressSpaceAssigned.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 251 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab.Validator.Network.Azure_Network
{
public class AzureVnetAddressSpaceTooSmall : LabValidator, IValidate
{
public AzureVnetAddressSpaceTooSmall()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var vnets = lab.VirtualNetworks.Where(adapter => adapter.HostType == VirtualizationHost.Azure && adapter.Subnets.Count > 0);
if (vnets.Count() == 0)
yield break;
foreach (var vnet in vnets)
{
if (vnet.Subnets.Count > 1 && vnet.Subnets.Where(sn => sn.AddressSpace.Cidr >= vnet.AddressSpace.Cidr).Count() > 0 ||
vnet.Subnets.Count == 1 && vnet.Subnets.Where(sn => sn.AddressSpace.Cidr > vnet.AddressSpace.Cidr).Count() > 0)
{
yield return new ValidationMessage
{
Message = "At least one subnet's address space is bigger or equal to the virtual network's address space.",
HelpText = "Reexamine the CIDR of your Azure virtual network and the subnets you have configured. If you configure more than one subnet, make sure that the address space fits your subnets.",
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/Azure Network/AzureVnetAddressSpaceTooSmall.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 307 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// If DCs are installed on Azure there must be a DNS server configured on the connected Virtual Network Site.
/// </summary>
public class AzureVnetDnsServerRequiredForActiveDirectory : LabValidator, IValidate
{
public AzureVnetDnsServerRequiredForActiveDirectory()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
//get all domain controllers
var dcs = lab.Machines.Where(machine => machine.HostType == VirtualizationHost.Azure && (machine.Roles.Where(role => (role.Name & (Roles.RootDC | Roles.FirstChildDC | Roles.DC)) == role.Name).Count() == 1));
//get all VNets with no DNS configured
var vnetsWithNoDns = lab.VirtualNetworks.Where(vnet => vnet.HostType == VirtualizationHost.Azure && vnet.DnsServers.Count == 0);
if (dcs.Count() == 0 | vnetsWithNoDns.Count() == 0)
yield break;
foreach (var vnet in vnetsWithNoDns)
{
yield return new ValidationMessage
{
Message = "Active Directory is configured in the lab but no DNS server is assigned on the VNet",
TargetObject = vnet.Name,
Type = MessageType.Error
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/Azure Network/AzureVnetDnsServerRequiredForActiveDirectory.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 324 |
```smalltalk
using System.Collections.Generic;
using System.Linq;
namespace AutomatedLab
{
/// <summary>
/// If DCs are installed on Azure there must be a DNS server configured on the connected Virtual Network Site.
/// </summary>
public class AzureVnetDnsServerInvalid : LabValidator, IValidate
{
public AzureVnetDnsServerInvalid()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
//get all domain controllers
var dcs = lab.Machines.Where(machine => machine.HostType == VirtualizationHost.Azure && (machine.Roles.Where(role => (role.Name & (Roles.RootDC | Roles.FirstChildDC | Roles.DC)) == role.Name).Count() == 1));
//get all VNets with no DNS configured
var vnetsWithDns = lab.VirtualNetworks.Where(vnet => vnet.HostType == VirtualizationHost.Azure && vnet.DnsServers.Count > 0);
if (dcs.Count() == 0 | vnetsWithDns.Count() == 0)
yield break;
var dcIpAddresses = dcs.SelectMany(dc => dc.NetworkAdapters).SelectMany(na => na.Ipv4Address).Select(ip => ip.IpAddress).ToList();
foreach (var vnet in vnetsWithDns)
{
foreach (var ip in vnet.DnsServers)
{
if (!dcIpAddresses.Contains(ip))
yield return new ValidationMessage
{
Message = string.Format("The DNS server '{0}' configured on the VNet is probably not the right one. Make sure you point to a DNS server inside the lab.", ip),
TargetObject = vnet.Name,
Type = MessageType.Warning
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/Azure Network/AzureVnetDnsServerInvalid.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 382 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// Check if the an external switch connects to a WiFi adapter. This is not supported.
/// </summary>
public class ExternalSwitchConnectsWifi : LabValidator, IValidate
{
public ExternalSwitchConnectsWifi()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var externalSwitches = lab.VirtualNetworks.Where(sw => sw.SwitchType == SwitchType.External);
if (externalSwitches.Count() == 0)
yield break;
var networkAdapters = LabXml.PowerShellHelper.InvokeCommand("Get-NetAdapter");
foreach (var networkSwitch in lab.VirtualNetworks.Where(sw => sw.SwitchType == SwitchType.External))
{
var networkAdapter = networkAdapters.Where(na => na.Properties["InterfaceType"].Value.ToString() == "71" && na.Properties["Name"].Value.ToString().ToLower() == networkSwitch.Name.ToLower());
if (networkAdapter.Count() == 1)
{
yield return new ValidationMessage
{
Message = string.Format("The specified physical adapter '{0}' is a Wi-Fi adapter which is not supprted", networkSwitch.AdapterName),
TargetObject = networkSwitch.Name,
Type = MessageType.Error,
HelpText = "Connect the external switch to a non-WiFi adapter"
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/ExternalSwitchConnectsWifi.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 324 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class AzureVnetConnectsToUnknownVnet : LabValidator, IValidate
{
public AzureVnetConnectsToUnknownVnet()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var vnets = lab.VirtualNetworks.Where(adapter => adapter.HostType == VirtualizationHost.Azure && adapter.ConnectToVnets.Count > 0);
if (vnets.Count() == 0)
yield break;
foreach (var vnet in vnets)
{
var unknownVnets = vnet.ConnectToVnets.Except(vnets.Select(v => v.Name).ToList());
if (unknownVnets.Count() > 0)
{
yield return new ValidationMessage
{
Message = string.Format("The Azure VNet {0} connects to VNet(s) that is / are unknown: {1}", vnet.Name, string.Join(", ", unknownVnets)),
TargetObject = vnet.Name,
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/Azure Network/AzureVnetConnectsToUnknownVnet.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 285 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// DHCP is not supported on external switches.
/// </summary>
public class DuplicateAdapterAddressSpace : LabValidator, IValidate
{
public DuplicateAdapterAddressSpace()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var networks = lab.VirtualNetworks.Where(vn => vn.SwitchType != SwitchType.External).ToList();
var vswitches = LabXml.PowerShellHelper.InvokeCommand(
"Get-LabVirtualNetwork"
);
foreach (var vswitch in vswitches)
{
var overlappingAddress = networks.FirstOrDefault(nw => !nw.ResourceName.Equals(vswitch.Properties["ResourceName"].ToString()) && nw.AddressSpace.ToString().Equals(vswitch.Properties["AddressSpace"].ToString()));
if (null != overlappingAddress)
{
yield return new ValidationMessage
{
Message = string.Format("Duplicate address space. Existing adapter {0} has same address space ({1}) as {2}", vswitch.Properties["ResourceName"],overlappingAddress.AddressSpace, overlappingAddress.ResourceName),
TargetObject = "Internal or private switch",
Type = MessageType.Error,
HelpText = "Change the address space specified in Add-LabVirtualNetworkDefinition"
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/DuplicateAdapterAddressSpace.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 302 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// Check if the specified network adapter for the external switches exists and generate an error if it does not.
/// </summary>
public class ExternalSwitchNetworkAdapterExists : LabValidator, IValidate
{
public ExternalSwitchNetworkAdapterExists()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var externalSwitches = lab.VirtualNetworks.Where(sw => sw.SwitchType == SwitchType.External);
if (externalSwitches.Count() == 0)
yield break;
var networkAdapters = LabXml.PowerShellHelper.InvokeCommand("Get-NetAdapter");
foreach (var networkSwitch in externalSwitches)
{
var networkAdapter = networkAdapters.Where(na => na.Properties["InterfaceType"].Value.ToString() == "6" && na.Properties["Name"].Value.ToString().ToLower() == networkSwitch.ResourceName.ToLower());
if (networkAdapters.Count() == 0)
{
yield return new ValidationMessage
{
Message = string.Format("The specified physical non-Wi-Fi adapter '{0}' does not exist", networkSwitch.AdapterName),
TargetObject = networkSwitch.ResourceName,
Type = MessageType.Error
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/ExternalSwitchNetworkAdapterExists.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 296 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// The routing role must be in a root domain or non domain joined.
/// </summary>
public class RoutingRoleMustBeInRootDomainy : LabValidator, IValidate
{
public RoutingRoleMustBeInRootDomainy()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var routers = machines.Where(m => m.Roles.Select(r => r.Name).Contains(Roles.Routing) && m.IsDomainJoined).ToList();
foreach (var router in routers.Where(m => !lab.IsRootDomain(m.DomainName)))
{
yield return new ValidationMessage
{
Message = string.Format("The routing role must be in a root domain or non domain joined. The router '{0}' is in domain '{1}'", router.Name, router.DomainName),
TargetObject = router.Name,
Type = MessageType.Error,
HelpText = "Put the router in one of the root domains."
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/RoutingRoleMustBeInRootDomainy.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 241 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// check if the new external switch should be bound to a network adapter that is bridged already.
/// </summary>
public class ExternalSwitchNetworkAdapterBridgedAlready : LabValidator, IValidate
{
public ExternalSwitchNetworkAdapterBridgedAlready()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var newExternalSwitches = lab.VirtualNetworks.Where(sw => sw.SwitchType == SwitchType.External);
if (newExternalSwitches.Count() == 0)
yield break;
var existingExternalSwitches = LabXml.PowerShellHelper.InvokeCommand(
"Get-VMSwitch -SwitchType External | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name ConnectionName -Value (Get-NetAdapter -InterfaceDescription $_.NetAdapterInterfaceDescription).Name -PassThru }"
);
foreach (var existingExternalSwitch in existingExternalSwitches)
{
if (newExternalSwitches.Select(sw => sw.AdapterName).Contains(existingExternalSwitch.Properties["ConnectionName"].Value))
{
yield return new ValidationMessage
{
Message = string.Format("The network connection '{0}' is already bridged to virtual switch '{1}'", existingExternalSwitch.Properties["ConnectionName"].Value, existingExternalSwitch.Properties["Name"].Value),
TargetObject = existingExternalSwitch.Properties["ConnectionName"].Value.ToString(),
Type = MessageType.Warning
};
}
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/ExternalSwitchNetworkAdapterBridgedAlready.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 346 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// DHCP is not supported on external switches.
/// </summary>
public class ExternalSwitchNoDhcp : LabValidator, IValidate
{
public ExternalSwitchNoDhcp()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var dhcpServers = machines.Where(m => m.Roles.Select(r => r.Name).Contains(Roles.DHCP)).ToList();
var externalSwitches = lab.VirtualNetworks.Where(adapter => adapter.SwitchType == SwitchType.External);
if (externalSwitches.Count() > 0 && dhcpServers.Count() > 0)
{
yield return new ValidationMessage
{
Message = "DHCP servers are not supported when using external virtual switches",
TargetObject = "External Network Switch",
Type = MessageType.Error,
HelpText = "Remove the DHCP server which is connected to the external switch."
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/ExternalSwitchNoDhcp.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 231 |
```smalltalk
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace AutomatedLab
{
/// <summary>
/// New external switch has a name collision with an already exisitng private or internal one.
/// </summary>
public class ExternalSwitchNameCollision : LabValidator, IValidate
{
public ExternalSwitchNameCollision()
{
messageContainer = RunValidation();
}
public override IEnumerable<ValidationMessage> Validate()
{
var externalSwitches = lab.VirtualNetworks.Where(adapter => adapter.SwitchType == SwitchType.External);
if (externalSwitches.Count() == 0)
yield break;
var existingExternalSwitches = LabXml.PowerShellHelper.InvokeCommand("Get-VMSwitch -SwitchType External | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name ConnectionName -Value (Get-NetAdapter -InterfaceDescription $_.NetAdapterInterfaceDescription).Name -PassThru }");
var existingSwitches = LabXml.PowerShellHelper.InvokeCommand("Get-VMSwitch");
var existingSwitchNames = existingSwitches.Where(sw => sw.Properties["SwitchType"].Value.ToString() == "Internal" | sw.Properties["SwitchType"].Value.ToString() == "Private").Select(sw => sw.Properties["Name"].Value.ToString());
foreach (var sw in lab.VirtualNetworks.Where(sw => existingSwitchNames.Contains(sw.Name)))
{
yield return new ValidationMessage
{
Message = "There is already a virtual switch with the same name but a different switch type",
TargetObject = sw.Name,
Type = MessageType.Warning
};
}
}
}
}
``` | /content/code_sandbox/LabXml/Validator/Network/HyperV Network/ExternalSwitchNameCollision.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 352 |
```smalltalk
using System;
using System.Collections;
using System.Linq;
using System.Net;
namespace AutomatedLab
{
[Serializable]
public class AzureSubnet
{
private string name;
private IPNetwork addressSpace;
public string Name
{
get { return name; }
set { name = value; }
}
public IPNetwork AddressSpace
{
get { return addressSpace; }
set { addressSpace = value; }
}
public override string ToString()
{
return name;
}
public static implicit operator AzureSubnet(Hashtable ht)
{
if (ht.Keys.OfType<string>().Where(k => k == "SubnetName" | k == "SubnetAddressPrefix").Count() != 2)
{
return null;
}
var subnet = new AzureSubnet();
subnet.name = ht["SubnetName"].ToString();
subnet.addressSpace = ht["SubnetAddressPrefix"].ToString();
return subnet;
}
}
}
``` | /content/code_sandbox/LabXml/Network/AzureSubnet.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 213 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public class VirtualNetwork
{
private string name;
private IPNetwork addressSpace;
private SwitchType switchType;
private string adapterName;
private string locationName;
private VirtualizationHost hostType;
private List<AzureSubnet> subnets = new List<AzureSubnet>();
private List<string> connectToVnets = new List<string>();
private List<IPAddress> dnsServers = new List<IPAddress>();
private List<IPAddress> issuedIpAddresses = new List<IPAddress>();
private AutomatedLab.NetworkAdapter managementAdapter = new AutomatedLab.NetworkAdapter();
private bool enableManagementAdapter;
private SerializableDictionary<string, string> notes;
[XmlAttribute]
public string AzureDnsLabel {get; set;}
public List<AzureSubnet> Subnets
{
get { return subnets; }
set { subnets = value; }
}
public string FriendlyName { get; set; }
public string ResourceName
{
get
{
if (!string.IsNullOrWhiteSpace(FriendlyName)) { return FriendlyName; } else { return Name; }
}
}
[XmlAttribute]
public string Name
{
get { return name; }
set { name = value; }
}
public IPNetwork AddressSpace
{
get { return addressSpace; }
set { addressSpace = value; }
}
[XmlAttribute]
public SwitchType SwitchType
{
get { return switchType; }
set { switchType = value; }
}
[XmlAttribute]
public string AdapterName
{
get { return adapterName; }
set { adapterName = value; }
}
[XmlAttribute]
public string LocationName
{
get { return locationName; }
set { locationName = value; }
}
[XmlAttribute]
public VirtualizationHost HostType
{
get { return hostType; }
set { hostType = value; }
}
public List<string> ConnectToVnets
{
get { return connectToVnets; }
set { connectToVnets = value; }
}
// Allowing Azure users to peer to a non-AL-managed VNET
public List<string> PeeringVnetResourceIds { get; set; }
public List<IPAddress> DnsServers
{
get { return dnsServers; }
set { dnsServers = value; }
}
public List<IPAddress> IssuedIpAddresses
{
get { return issuedIpAddresses; }
set { issuedIpAddresses = value; }
}
public AutomatedLab.NetworkAdapter ManagementAdapter
{
get { return managementAdapter; }
set { managementAdapter = value; }
}
[XmlAttribute]
public bool EnableManagementAdapter
{
get { return enableManagementAdapter; }
set { enableManagementAdapter = value; }
}
public VirtualNetwork()
{
SwitchType = SwitchType.Internal;
enableManagementAdapter = true;
}
public override string ToString()
{
return name;
}
public IPAddress NextIpAddress()
{
IPAddress ip = null;
if (issuedIpAddresses.Count == 0)
{
ip = addressSpace.Network.Increment().Increment().Increment();
issuedIpAddresses.Add(ip);
}
else
{
ip = issuedIpAddresses.TakeLast().Increment();
issuedIpAddresses.Add(ip);
}
while (HostType == VirtualizationHost.Azure && issuedIpAddresses.Count < 5)
{
ip = issuedIpAddresses.TakeLast().Increment();
issuedIpAddresses.Add(ip);
}
ip.isAutoGenerated = true;
return ip;
}
public SerializableDictionary<string, string> Notes
{
get { return notes; }
set { notes = value; }
}
}
}
``` | /content/code_sandbox/LabXml/Network/VirtualNetwork.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 845 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace AutomatedLab
{
public static class SubnetHelper
{
public static readonly IPAddress ClassA = "255.0.0.0";
public static readonly IPAddress ClassB = "255.255.0.0";
public static readonly IPAddress ClassC = "255.255.255.0";
public static IPAddress CreateByHostBitLength(int hostpartLength)
{
int hostPartLength = hostpartLength;
int netPartLength = 32 - hostPartLength;
if (netPartLength < 2)
throw new ArgumentException("Number of hosts is to large for IPv4");
byte[] binaryMask = new byte[4];
for (int i = 0; i < 4; i++)
{
if (i * 8 + 8 <= netPartLength)
binaryMask[i] = 255;
else if (i * 8 > netPartLength)
binaryMask[i] = 0;
else
{
int oneLength = netPartLength - i * 8;
string binaryDigit =
string.Empty.PadLeft(oneLength, '1').PadRight(8, '0');
binaryMask[i] = Convert.ToByte(binaryDigit, 2);
}
}
return new IPAddress(binaryMask);
}
public static IPAddress CreateByNetBitLength(int netpartLength)
{
int hostPartLength = 32 - netpartLength;
return CreateByHostBitLength(hostPartLength);
}
public static IPAddress CreateByHostNumber(int numberOfHosts)
{
int maxNumber = numberOfHosts + 1;
string b = Convert.ToString(maxNumber, 2);
return CreateByHostBitLength(b.Length);
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddressExtensions.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 390 |
```smalltalk
using System.Collections.Generic;
using System.Collections;
using System.Numerics;
using System.Net.Sockets;
using System;
/// <summary>
/// Code taken from path_to_url on 2015 10 26
/// </summary>
namespace AutomatedLab
{
public class IPNetworkCollection : IEnumerable<IPNetwork>, IEnumerator<IPNetwork>
{
private BigInteger _enumerator;
private byte _cidrSubnet;
private IPNetwork _ipnetwork;
private byte _cidr
{
get { return this._ipnetwork.Cidr; }
}
private BigInteger _broadcast
{
get { return IPNetwork.ToBigInteger(this._ipnetwork.Broadcast); }
}
private BigInteger _lastUsable
{
get { return IPNetwork.ToBigInteger(this._ipnetwork.LastUsable); }
}
private BigInteger _network
{
get { return IPNetwork.ToBigInteger(this._ipnetwork.Network); }
}
internal IPNetworkCollection(IPNetwork ipnetwork, byte cidrSubnet)
{
int maxCidr = ipnetwork.AddressFamily == AddressFamily.InterNetwork ? 32 : 128;
if (cidrSubnet > maxCidr)
{
throw new ArgumentOutOfRangeException("cidrSubnet");
}
if (cidrSubnet < ipnetwork.Cidr)
{
throw new ArgumentException("cidr");
}
this._cidrSubnet = cidrSubnet;
this._ipnetwork = ipnetwork;
this._enumerator = -1;
}
#region Count, Array, Enumerator
public BigInteger Count
{
get
{
BigInteger count = BigInteger.Pow(2, this._cidrSubnet - this._cidr);
return count;
}
}
public IPNetwork this[BigInteger i]
{
get
{
if (i >= this.Count)
{
throw new ArgumentOutOfRangeException("i");
}
BigInteger last = this._ipnetwork.AddressFamily == AddressFamily.InterNetworkV6
? this._lastUsable : this._broadcast;
BigInteger increment = (last - this._network) / this.Count;
BigInteger uintNetwork = this._network + ((increment + 1) * i);
IPNetwork ipn = new IPNetwork(uintNetwork, this._ipnetwork.AddressFamily, this._cidrSubnet);
return ipn;
}
}
#endregion
#region IEnumerable Members
IEnumerator<IPNetwork> IEnumerable<IPNetwork>.GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
#region IEnumerator<IPNetwork> Members
public IPNetwork Current
{
get { return this[this._enumerator]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose
return;
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get { return this.Current; }
}
public bool MoveNext()
{
this._enumerator++;
if (this._enumerator >= this.Count)
{
return false;
}
return true;
}
public void Reset()
{
this._enumerator = -1;
}
#endregion
#endregion
}
}
``` | /content/code_sandbox/LabXml/Network/IPNetworkCollection.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 701 |
```smalltalk
using System.Collections.Generic;
using System.Collections;
using System.Numerics;
using System;
using System.Net.Sockets;
/// <summary>
/// Code taken from path_to_url on 2015 10 26
/// </summary>
namespace AutomatedLab
{
public class IPAddressCollection : IEnumerable<IPAddress>, IEnumerator<IPAddress>
{
private IPNetwork _ipnetwork;
private BigInteger _enumerator;
internal IPAddressCollection(IPNetwork ipnetwork)
{
this._ipnetwork = ipnetwork;
this._enumerator = -1;
}
#region Count, Array, Enumerator
public BigInteger Count
{
get
{
return this._ipnetwork.Total;
}
}
public IPAddress this[BigInteger i]
{
get
{
if (i >= this.Count)
{
throw new ArgumentOutOfRangeException("i");
}
byte width = this._ipnetwork.AddressFamily == AddressFamily.InterNetwork ? (byte)32 : (byte)128;
IPNetworkCollection ipn = IPNetwork.Subnet(this._ipnetwork, width);
return ipn[i].Network;
}
}
#endregion
#region IEnumerable Members
IEnumerator<IPAddress> IEnumerable<IPAddress>.GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
#region IEnumerator<IPNetwork> Members
public IPAddress Current
{
get { return this[this._enumerator]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose
return;
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get { return this.Current; }
}
public bool MoveNext()
{
this._enumerator++;
if (this._enumerator >= this.Count)
{
return false;
}
return true;
}
public void Reset()
{
this._enumerator = -1;
}
#endregion
#endregion
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddressCollection.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 427 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace AutomatedLab
{
public partial class IPNetwork
{
private IPAddress ipAddress;
public static implicit operator IPNetwork(string ipString)
{
IPNetwork network;
if (TryParse(ipString, out network))
{
return network;
}
else
throw new InvalidCastException("The input string could not be parsed");
}
public IPNetwork()
{ }
[XmlAttribute]
public string SerializationNetworkAddress
{
get { return _ipaddress.ToString(); }
set { _ipaddress = BigInteger.Parse(value); }
}
[XmlAttribute]
public AddressFamily SerializationAddressFamily
{
get { return _family; }
set { _family = value; }
}
[XmlAttribute]
public byte SerializationCidr
{
get { return _cidr; }
set { _cidr = value; }
}
[XmlElement]
public IPAddress IpAddress
{
get { return ipAddress; }
set { ipAddress = value; }
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPNetwork Class/IPNetwork2.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 258 |
```smalltalk
/// <summary>
/// Code taken from path_to_url on 2015 10 26
/// </summary>
namespace AutomatedLab
{
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
/// <summary>
/// Extension methods to convert <see cref="System.Numerics.BigInteger"/>
/// instances to hexadecimal, octal, and binary strings.
/// </summary>
public static class BigIntegerExtensions
{
/// <summary>
/// Converts a <see cref="BigInteger"/> to a binary string.
/// </summary>
/// <param name="bigint">A <see cref="BigInteger"/>.</param>
/// <returns>
/// A <see cref="System.String"/> containing a binary
/// representation of the supplied <see cref="BigInteger"/>.
/// </returns>
public static string ToBinaryString(this BigInteger bigint)
{
var bytes = bigint.ToByteArray();
var idx = bytes.Length - 1;
// Create a StringBuilder having appropriate capacity.
var base2 = new StringBuilder(bytes.Length * 8);
// Convert first byte to binary.
var binary = Convert.ToString(bytes[idx], 2);
// Ensure leading zero exists if value is positive.
if (binary[0] != '0' && bigint.Sign == 1)
{
base2.Append('0');
}
// Append binary string to StringBuilder.
base2.Append(binary);
// Convert remaining bytes adding leading zeros.
for (idx--; idx >= 0; idx--)
{
base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));
}
return base2.ToString();
}
/// <summary>
/// Converts a <see cref="BigInteger"/> to a hexadecimal string.
/// </summary>
/// <param name="bigint">A <see cref="BigInteger"/>.</param>
/// <returns>
/// A <see cref="System.String"/> containing a hexadecimal
/// representation of the supplied <see cref="BigInteger"/>.
/// </returns>
public static string ToHexadecimalString(this BigInteger bigint)
{
return bigint.ToString("X");
}
/// <summary>
/// Converts a <see cref="BigInteger"/> to a octal string.
/// </summary>
/// <param name="bigint">A <see cref="BigInteger"/>.</param>
/// <returns>
/// A <see cref="System.String"/> containing an octal
/// representation of the supplied <see cref="BigInteger"/>.
/// </returns>
public static string ToOctalString(this BigInteger bigint)
{
var bytes = bigint.ToByteArray();
var idx = bytes.Length - 1;
// Create a StringBuilder having appropriate capacity.
var base8 = new StringBuilder(((bytes.Length / 3) + 1) * 8);
// Calculate how many bytes are extra when byte array is split
// into three-byte (24-bit) chunks.
var extra = bytes.Length % 3;
// If no bytes are extra, use three bytes for first chunk.
if (extra == 0)
{
extra = 3;
}
// Convert first chunk (24-bits) to integer value.
int int24 = 0;
for (; extra != 0; extra--)
{
int24 <<= 8;
int24 += bytes[idx--];
}
// Convert 24-bit integer to octal without adding leading zeros.
var octal = Convert.ToString(int24, 8);
// Ensure leading zero exists if value is positive.
if (octal[0] != '0' && bigint.Sign == 1)
{
base8.Append('0');
}
// Append first converted chunk to StringBuilder.
base8.Append(octal);
// Convert remaining 24-bit chunks, adding leading zeros.
for (; idx >= 0; idx -= 3)
{
int24 = (bytes[idx] << 16) + (bytes[idx - 1] << 8) + bytes[idx - 2];
base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0'));
}
return base8.ToString();
}
/// <summary>
///
/// Reverse a Positive BigInteger ONLY
/// Bitwise ~ operator
///
/// Input : FF FF FF FF
/// Width : 4
/// Result : 00 00 00 00
///
///
/// Input : 00 00 00 00
/// Width : 4
/// Result : FF FF FF FF
///
/// Input : FF FF FF FF
/// Width : 8
/// Result : FF FF FF FF 00 00 00 00
///
///
/// Input : 00 00 00 00
/// Width : 8
/// Result : FF FF FF FF FF FF FF FF
///
/// </summary>
/// <param name="input"></param>
/// <param name="width"></param>
/// <returns></returns>
public static BigInteger PositiveReverse(this BigInteger input, int width)
{
var result = new List<byte>();
var bytes = input.ToByteArray();
var work = new byte[width];
Array.Copy(bytes, 0, work, 0, bytes.Length - 1); // Length -1 : positive BigInteger
for (int i = 0; i < work.Length; i++)
{
result.Add((byte)(~work[i]));
}
result.Add(0); // positive BigInteger
return new BigInteger(result.ToArray());
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPNetwork Class/BigIntegerExt.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,222 |
```smalltalk
using System;
using System.Xml.Serialization;
namespace AutomatedLab
{
public partial class IPAddress
{
//private int ipv4Prefix;
//public int Ipv4Prefix
//{
// get { return ipv4Prefix; }
// set { ipv4Prefix = value; }
//}
//public IPAddress Ipv4Subnet
//{
// get
// {
// if (ipv4Prefix != 0)
// {
// return GetByNetBitLength(ipv4Prefix);
// }
// else
// {
// return "0.0.0.0";
// }
// }
//}
//public static IPAddress GetByHostBitLength(int hostpartLength)
//{
// int hostPartLength = hostpartLength;
// int netPartLength = 32 - hostPartLength;
// if (netPartLength < 2)
// throw new ArgumentException("Number of hosts is to large for IPv4");
// byte[] binaryMask = new byte[4];
// for (int i = 0; i < 4; i++)
// {
// if (i * 8 + 8 <= netPartLength)
// binaryMask[i] = 255;
// else if (i * 8 > netPartLength)
// binaryMask[i] = 0;
// else
// {
// int oneLength = netPartLength - i * 8;
// string binaryDigit =
// string.Empty.PadLeft(oneLength, '1').PadRight(8, '0');
// binaryMask[i] = Convert.ToByte(binaryDigit, 2);
// }
// }
// return new IPAddress(binaryMask);
//}
//public static IPAddress GetByNetBitLength(int netpartLength)
//{
// int hostPartLength = 32 - netpartLength;
// return GetByHostBitLength(hostPartLength);
//}
//public static IPAddress GetByHostNumber(int numberOfHosts)
//{
// int maxNumber = numberOfHosts + 1;
// string b = Convert.ToString(maxNumber, 2);
// return GetByHostBitLength(b.Length);
//}
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddress Class/IPAddress Subnet.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 513 |
```smalltalk
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomatedLab
{
public partial class IPAddress
{
//public IPAddress GetBroadcastAddress()
//{
// byte[] ipAdressBytes = GetAddressBytes();
// byte[] subnetMaskBytes = Ipv4Subnet.GetAddressBytes();
// if (ipAdressBytes.Length != subnetMaskBytes.Length)
// throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
// byte[] broadcastAddress = new byte[ipAdressBytes.Length];
// for (int i = 0; i < broadcastAddress.Length; i++)
// {
// broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
// }
// return new IPAddress(broadcastAddress);
//}
//public IPAddress GetNetworkAddress()
//{
// byte[] ipAdressBytes = ip.GetAddressBytes();
// byte[] subnetMaskBytes = Ipv4Subnet.GetAddressBytes();
// if (ipAdressBytes.Length != subnetMaskBytes.Length)
// throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
// byte[] broadcastAddress = new byte[ipAdressBytes.Length];
// for (int i = 0; i < broadcastAddress.Length; i++)
// {
// broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
// }
// var networkAddress = new IPAddress(broadcastAddress);
// networkAddress.ipv4Prefix = ipv4Prefix;
// return networkAddress;
//}
//public bool IsInSameSubnet(IPAddress address)
//{
// IPAddress network1 = GetNetworkAddress();
// IPAddress network2 = address.GetNetworkAddress();
// return network1.Equals(network2);
//}
//public uint ToDecimal()
//{
// var i = 3;
// uint decimalIp = 0;
// foreach (var b in ip.GetAddressBytes())
// {
// decimalIp += Convert.ToUInt32(b * Math.Pow(256, i));
// i--;
// }
// return decimalIp;
//}
//public string ToBinary()
//{
// var elements = ip.GetAddressBytes().ForEach(b => Convert.ToString(b, 2).PadLeft(8, '0')).ToArray();
// return string.Join(".", elements);
//}
public IPAddress Increment()
{
byte[] ip = GetAddressBytes();
ip[3]++;
if (ip[3] == 0)
{
ip[2]++;
if (ip[2] == 0)
{
ip[1]++;
if (ip[1] == 0)
ip[0]++;
}
}
return new IPAddress(ip);
}
public IPAddress Increment(int iterations)
{
IPAddress tempIp = ip ;
for (int i = 0; i < iterations; i++)
{
tempIp = tempIp.Increment();
}
return tempIp;
}
public IPAddress Decrement()
{
byte[] ip = GetAddressBytes();
ip[3]--;
if (ip[3] == 0)
{
ip[2]--;
if (ip[2] == 0)
{
ip[1]--;
if (ip[1] == 0)
ip[0]--;
}
}
return new IPAddress(ip);
}
public IPAddress Decrement(int iterations)
{
IPAddress tempIp = ip;
for (int i = 0; i < iterations; i++)
{
tempIp = tempIp.Decrement();
}
return tempIp;
}
public static implicit operator IPAddress(string ipString)
{
IPAddress ip;
if (ipString.Contains("/"))
{
ipString = ipString.Substring(0, ipString.IndexOf('/'));
}
if (TryParse(ipString, out ip))
{
return ip;
}
else
throw new InvalidCastException();
}
public static implicit operator System.Net.IPAddress(IPAddress ip)
{
return ip.ip;
}
public static implicit operator IPAddress(System.Net.IPAddress ip)
{
return new IPAddress(ip.GetAddressBytes());
}
public static bool operator ==(IPAddress a, object b)
{
return Equals(a, b);
}
public static bool operator !=(IPAddress a, object b)
{
return !Equals(a, b);
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddress Class/IPAddress Conversion.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,005 |
```smalltalk
using System;
using System.Linq;
using System.Xml.Serialization;
namespace AutomatedLab
{
[Serializable]
public partial class IPAddress
{
private System.Net.IPAddress ip;
public static IPAddress Any { get { return System.Net.IPAddress.Any; } }
public static IPAddress Broadcast { get { return System.Net.IPAddress.Broadcast; } }
public static IPAddress IPv6Any { get { return System.Net.IPAddress.IPv6Any; } }
public static IPAddress IPv6Loopback { get { return System.Net.IPAddress.IPv6Loopback; } }
public static IPAddress IPv6None { get { return System.Net.IPAddress.IPv6None; } }
public static IPAddress Loopback { get { return System.Net.IPAddress.Loopback; } }
public static IPAddress None { get { return System.Net.IPAddress.None; } }
[XmlAttribute]
public string AddressAsString
{
get
{
return ip.ToString();
}
set
{
ip = Parse(value);
}
}
public System.Net.Sockets.AddressFamily AddressFamily { get { return ip.AddressFamily; } }
public bool IsIPv4MappedToIPv6 { get { return ip.IsIPv4MappedToIPv6; } }
public bool IsIPv6LinkLocal { get { return ip.IsIPv6LinkLocal; } }
public bool IsIPv6Multicast { get { return ip.IsIPv6Multicast; } }
public bool IsIPv6SiteLocal { get { return ip.IsIPv6SiteLocal; } }
public bool IsIPv6Teredo { get { return ip.IsIPv6Teredo; } }
[XmlIgnore]
public long? ScopeId
{
get
{
try
{
return ip.ScopeId;
}
catch
{
return null;
}
}
set
{
if (value.HasValue)
ip.ScopeId = value.Value;
}
}
public static int HostToNetworkOrder(int host)
{
return System.Net.IPAddress.HostToNetworkOrder(host);
}
public static short HostToNetworkOrder(short host)
{
return System.Net.IPAddress.HostToNetworkOrder(host);
}
public static long HostToNetworkOrder(long host)
{
return System.Net.IPAddress.HostToNetworkOrder(host);
}
public static bool IsLoopback(IPAddress address)
{
return System.Net.IPAddress.IsLoopback(address);
}
public static int NetworkToHostOrder(int network)
{
return System.Net.IPAddress.NetworkToHostOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return System.Net.IPAddress.NetworkToHostOrder(network);
}
public static long NetworkToHostOrder(long network)
{
return System.Net.IPAddress.NetworkToHostOrder(network);
}
public static IPAddress Parse(string ipString)
{
IPAddress address = None;
address = System.Net.IPAddress.Parse(ipString);
return address;
}
public static bool TryParse(string ipString, out IPAddress address)
{
System.Net.IPAddress ip = None;
address = None;
var result = System.Net.IPAddress.TryParse(ipString, out ip);
if (result)
{
address = ip;
}
return result;
}
public override bool Equals(object comparand)
{
var ip = comparand as IPAddress;
if (ip == null)
return false;
var bytes1 = GetAddressBytes();
var bytes2 = ip.GetAddressBytes();
return bytes1.SequenceEqual(bytes2);
}
public byte[] GetAddressBytes()
{
return ip.GetAddressBytes();
}
public override int GetHashCode()
{
return ip.GetHashCode();
}
public IPAddress MapToIPv4()
{
return ip.MapToIPv4();
}
public IPAddress MapToIPv6()
{
return ip.MapToIPv6();
}
public IPAddress()
{
ip = new System.Net.IPAddress(0);
}
public IPAddress(long newAddress)
{
ip = new System.Net.IPAddress(newAddress);
}
public IPAddress(byte[] address)
{
ip = new System.Net.IPAddress(address);
}
public IPAddress(byte[] address, long scopeid)
{
ip = new System.Net.IPAddress(address, scopeid);
}
public override string ToString()
{
return ip.ToString();
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddress Class/IPAddress Defaults.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 944 |
```smalltalk
namespace AutomatedLab
{
public partial class IPAddress
{
internal bool isAutoGenerated;
public static IPAddress Null
{
get { return "0.0.0.0"; }
}
public bool IsAutoGenerated
{
get { return isAutoGenerated; }
}
}
}
``` | /content/code_sandbox/LabXml/Network/IPAddress Class/IPAddress AddOns.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 68 |
```smalltalk
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.IO;
using System.Numerics;
using System;
using System.Linq;
/// <summary>
/// Code taken from path_to_url on 2015 10 26
/// </summary>
namespace AutomatedLab
{
/// <summary>
/// IP Network utility class.
/// Use IPNetwork.Parse to create instances.
/// </summary>
[Serializable]
public partial class IPNetwork : IComparable<IPNetwork>
{
#region properties
//private uint _network;
private BigInteger _ipaddress;
private AddressFamily _family;
//private uint _netmask;
//private uint _broadcast;
//private uint _firstUsable;
//private uint _lastUsable;
//private uint _usable;
private byte _cidr;
#endregion
#region accessors
private BigInteger _network
{
get
{
BigInteger uintNetwork = this._ipaddress & this._netmask;
return uintNetwork;
}
}
/// <summary>
/// Network address
/// </summary>
public IPAddress Network
{
get
{
return IPNetwork.ToIPAddress(this._network, this._family);
}
}
/// <summary>
/// Address Family
/// </summary>
public AddressFamily AddressFamily
{
get
{
return this._family;
}
}
private BigInteger _netmask
{
get
{
return IPNetwork.ToUint(this._cidr, this._family);
}
}
/// <summary>
/// Netmask
/// </summary>
public IPAddress Netmask
{
get
{
return IPNetwork.ToIPAddress(this._netmask, this._family);
}
}
private BigInteger _broadcast
{
get
{
int width = this._family == AddressFamily.InterNetwork ? 4 : 16;
BigInteger uintBroadcast = this._network + this._netmask.PositiveReverse(width);
return uintBroadcast;
}
}
/// <summary>
/// Broadcast address
/// </summary>
public IPAddress Broadcast
{
get
{
if (this._family == AddressFamily.InterNetworkV6)
{
return null;
}
return IPNetwork.ToIPAddress(this._broadcast, this._family);
}
}
/// <summary>
/// First usable IP adress in Network
/// </summary>
public IPAddress FirstUsable
{
get
{
BigInteger fisrt = this._family == AddressFamily.InterNetworkV6
? this._network
: (this.Usable <= 0) ? this._network : this._network + 1;
return IPNetwork.ToIPAddress(fisrt, this._family);
}
}
/// <summary>
/// Last usable IP adress in Network
/// </summary>
public IPAddress LastUsable
{
get
{
BigInteger last = this._family == AddressFamily.InterNetworkV6
? this._broadcast
: (this.Usable <= 0) ? this._network : this._broadcast - 1;
return IPNetwork.ToIPAddress(last, this._family);
}
}
/// <summary>
/// Number of usable IP adress in Network
/// </summary>
public BigInteger Usable
{
get
{
if (this._family == AddressFamily.InterNetworkV6)
{
return this.Total;
}
byte[] mask = new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00 };
BigInteger bmask = new BigInteger(mask);
BigInteger usableIps = (_cidr > 30) ? 0 : ((bmask >> _cidr) - 1);
return usableIps;
}
}
/// <summary>
/// Number of IP adress in Network
/// </summary>
public BigInteger Total
{
get
{
int max = this._family == AddressFamily.InterNetwork ? 32 : 128;
BigInteger count = BigInteger.Pow(2, (max - _cidr));
return count;
}
}
/// <summary>
/// The CIDR netmask notation
/// </summary>
public byte Cidr
{
get
{
return this._cidr;
}
}
#endregion
#region constructor
internal IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr)
{
int maxCidr = family == AddressFamily.InterNetwork ? 32 : 128;
if (cidr > maxCidr)
{
throw new ArgumentOutOfRangeException("cidr");
}
_ipaddress = ipaddress;
this._family = family;
this._cidr = cidr;
}
#endregion
#region parsers
/// <summary>
/// 192.168.168.100 - 255.255.255.0
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <returns></returns>
public static IPNetwork Parse(string ipaddress, string netmask)
{
IPNetwork ipnetwork = null;
IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
ipnetwork.ipAddress = ipaddress;
return ipnetwork;
}
/// <summary>
/// 192.168.168.100/24
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static IPNetwork Parse(string ipaddress, byte cidr)
{
IPNetwork ipnetwork = null;
IPNetwork.InternalParse(false, ipaddress, cidr, out ipnetwork);
ipnetwork.ipAddress = ipaddress;
return ipnetwork;
}
/// <summary>
/// 192.168.168.100 255.255.255.0
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <returns></returns>
public static IPNetwork Parse(IPAddress ipaddress, IPAddress netmask)
{
IPNetwork ipnetwork = null;
IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
ipnetwork.ipAddress = ipaddress;
return ipnetwork;
}
/// <summary>
/// 192.168.0.1/24
/// 192.168.0.1 255.255.255.0
///
/// Network : 192.168.0.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.0.1
/// End : 192.168.0.254
/// Broadcast : 192.168.0.255
/// </summary>
/// <param name="network"></param>
/// <returns></returns>
public static IPNetwork Parse(string network)
{
IPNetwork ipnetwork = null;
IPNetwork.InternalParse(false, network, out ipnetwork);
ipnetwork.ipAddress = network;
return ipnetwork;
}
#endregion
#region TryParse
/// <summary>
/// 192.168.168.100 - 255.255.255.0
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <returns></returns>
public static bool TryParse(string ipaddress, string netmask, out IPNetwork ipnetwork)
{
IPNetwork ipnetwork2 = null;
IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
bool parsed = (ipnetwork2 != null);
ipnetwork = ipnetwork2;
ipnetwork.ipAddress = ipaddress;
return parsed;
}
/// <summary>
/// 192.168.168.100/24
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TryParse(string ipaddress, byte cidr, out IPNetwork ipnetwork)
{
IPNetwork ipnetwork2 = null;
IPNetwork.InternalParse(true, ipaddress, cidr, out ipnetwork2);
bool parsed = (ipnetwork2 != null);
ipnetwork = ipnetwork2;
ipnetwork.ipAddress = ipaddress;
return parsed;
}
/// <summary>
/// 192.168.0.1/24
/// 192.168.0.1 255.255.255.0
///
/// Network : 192.168.0.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.0.1
/// End : 192.168.0.254
/// Broadcast : 192.168.0.255
/// </summary>
/// <param name="network"></param>
/// <param name="ipnetwork"></param>
/// <returns></returns>
public static bool TryParse(string network, out IPNetwork ipnetwork)
{
IPNetwork ipnetwork2 = null;
IPNetwork.InternalParse(true, network, out ipnetwork2);
bool parsed = (ipnetwork2 != null);
ipnetwork = ipnetwork2;
ipnetwork.ipAddress = network;
return parsed;
}
/// <summary>
/// 192.168.0.1/24
/// 192.168.0.1 255.255.255.0
///
/// Network : 192.168.0.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.0.1
/// End : 192.168.0.254
/// Broadcast : 192.168.0.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <param name="ipnetwork"></param>
/// <returns></returns>
public static bool TryParse(IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
{
IPNetwork ipnetwork2 = null;
IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
bool parsed = (ipnetwork2 != null);
ipnetwork = ipnetwork2;
ipnetwork.ipAddress = ipaddress;
return parsed;
}
#endregion
#region InternalParse
/// <summary>
/// 192.168.168.100 - 255.255.255.0
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <returns></returns>
private static void InternalParse(bool tryParse, string ipaddress, string netmask, out IPNetwork ipnetwork)
{
if (string.IsNullOrEmpty(ipaddress))
{
if (tryParse == false)
{
throw new ArgumentNullException("ipaddress");
}
ipnetwork = null;
return;
}
if (string.IsNullOrEmpty(netmask))
{
if (tryParse == false)
{
throw new ArgumentNullException("netmask");
}
ipnetwork = null;
return;
}
IPAddress ip = null;
bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
if (ipaddressParsed == false)
{
if (tryParse == false)
{
throw new ArgumentException("ipaddress");
}
ipnetwork = null;
return;
}
IPAddress mask = null;
bool netmaskParsed = IPAddress.TryParse(netmask, out mask);
if (netmaskParsed == false)
{
if (tryParse == false)
{
throw new ArgumentException("netmask");
}
ipnetwork = null;
return;
}
IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
}
private static void InternalParse(bool tryParse, string network, out IPNetwork ipnetwork)
{
if (string.IsNullOrEmpty(network))
{
if (tryParse == false)
{
throw new ArgumentNullException("network");
}
ipnetwork = null;
return;
}
network = Regex.Replace(network, @"[^0-9a-f\.\/\s\:]+", "");
network = Regex.Replace(network, @"\s{2,}", " ");
network = network.Trim();
string[] args = network.Split(new char[] { ' ', '/' });
byte cidr = 0;
if (args.Length == 1)
{
if (IPNetwork.TryGuessCidr(args[0], out cidr))
{
IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
return;
}
if (tryParse == false)
{
throw new ArgumentException("network");
}
ipnetwork = null;
return;
}
if (byte.TryParse(args[1], out cidr))
{
IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
return;
}
IPNetwork.InternalParse(tryParse, args[0], args[1], out ipnetwork);
return;
}
/// <summary>
/// 192.168.168.100 255.255.255.0
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="netmask"></param>
/// <returns></returns>
private static void InternalParse(bool tryParse, IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
{
if (ipaddress == null)
{
if (tryParse == false)
{
throw new ArgumentNullException("ipaddress");
}
ipnetwork = null;
return;
}
if (netmask == null)
{
if (tryParse == false)
{
throw new ArgumentNullException("netmask");
}
ipnetwork = null;
return;
}
BigInteger uintIpAddress = IPNetwork.ToBigInteger(ipaddress);
byte? cidr2 = null;
bool parsed = IPNetwork.TryToCidr(netmask, out cidr2);
if (parsed == false)
{
if (tryParse == false)
{
throw new ArgumentException("netmask");
}
ipnetwork = null;
return;
}
byte cidr = (byte)cidr2;
IPNetwork ipnet = new IPNetwork(uintIpAddress, ipaddress.AddressFamily, cidr);
ipnetwork = ipnet;
return;
}
/// <summary>
/// 192.168.168.100/24
///
/// Network : 192.168.168.0
/// Netmask : 255.255.255.0
/// Cidr : 24
/// Start : 192.168.168.1
/// End : 192.168.168.254
/// Broadcast : 192.168.168.255
/// </summary>
/// <param name="ipaddress"></param>
/// <param name="cidr"></param>
/// <returns></returns>
private static void InternalParse(bool tryParse, string ipaddress, byte cidr, out IPNetwork ipnetwork)
{
if (string.IsNullOrEmpty(ipaddress))
{
if (tryParse == false)
{
throw new ArgumentNullException("ipaddress");
}
ipnetwork = null;
return;
}
IPAddress ip = null;
bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
if (ipaddressParsed == false)
{
if (tryParse == false)
{
throw new ArgumentException("ipaddress");
}
ipnetwork = null;
return;
}
IPAddress mask = null;
bool parsedNetmask = IPNetwork.TryToNetmask(cidr, ip.AddressFamily, out mask);
if (parsedNetmask == false)
{
if (tryParse == false)
{
throw new ArgumentException("cidr");
}
ipnetwork = null;
return;
}
IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
}
#endregion
#region converters
#region ToUint
/// <summary>
/// Convert an ipadress to decimal
/// 0.0.0.0 -> 0
/// 0.0.1.0 -> 256
/// </summary>
/// <param name="ipaddress"></param>
/// <returns></returns>
public static BigInteger ToBigInteger(IPAddress ipaddress)
{
BigInteger? uintIpAddress = null;
IPNetwork.InternalToBigInteger(false, ipaddress, out uintIpAddress);
return (BigInteger)uintIpAddress;
}
/// <summary>
/// Convert an ipadress to decimal
/// 0.0.0.0 -> 0
/// 0.0.1.0 -> 256
/// </summary>
/// <param name="ipaddress"></param>
/// <returns></returns>
public static bool TryToBigInteger(IPAddress ipaddress, out BigInteger? uintIpAddress)
{
BigInteger? uintIpAddress2 = null;
IPNetwork.InternalToBigInteger(true, ipaddress, out uintIpAddress2);
bool parsed = (uintIpAddress2 != null);
uintIpAddress = uintIpAddress2;
return parsed;
}
private static void InternalToBigInteger(bool tryParse, IPAddress ipaddress, out BigInteger? uintIpAddress)
{
if (ipaddress == null)
{
if (tryParse == false)
{
throw new ArgumentNullException("ipaddress");
}
uintIpAddress = null;
return;
}
byte[] bytes = ipaddress.GetAddressBytes();
if (bytes.Length != 4 && bytes.Length != 16)
{
if (tryParse == false)
{
throw new ArgumentException("bytes");
}
uintIpAddress = null;
return;
}
Array.Reverse(bytes);
var unsigned = new List<byte>(bytes);
unsigned.Add(0);
uintIpAddress = new BigInteger(unsigned.ToArray());
return;
}
/// <summary>
/// Convert a cidr to BigInteger netmask
/// </summary>
/// <param name="cidr"></param>
/// <returns></returns>
public static BigInteger ToUint(byte cidr, AddressFamily family)
{
BigInteger? uintNetmask = null;
IPNetwork.InternalToBigInteger(false, cidr, family, out uintNetmask);
return (BigInteger)uintNetmask;
}
/// <summary>
/// Convert a cidr to uint netmask
/// </summary>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TryToUint(byte cidr, AddressFamily family, out BigInteger? uintNetmask)
{
BigInteger? uintNetmask2 = null;
IPNetwork.InternalToBigInteger(true, cidr, family, out uintNetmask2);
bool parsed = (uintNetmask2 != null);
uintNetmask = uintNetmask2;
return parsed;
}
/// <summary>
/// Convert a cidr to uint netmask
/// </summary>
/// <param name="cidr"></param>
/// <returns></returns>
private static void InternalToBigInteger(bool tryParse, byte cidr, AddressFamily family, out BigInteger? uintNetmask)
{
if (family == AddressFamily.InterNetwork && cidr > 32)
{
if (tryParse == false)
{
throw new ArgumentOutOfRangeException("cidr");
}
uintNetmask = null;
return;
}
if (family == AddressFamily.InterNetworkV6 && cidr > 128)
{
if (tryParse == false)
{
throw new ArgumentOutOfRangeException("cidr");
}
uintNetmask = null;
return;
}
if (family != AddressFamily.InterNetwork
&& family != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(family.ToString());
}
if (family == AddressFamily.InterNetwork)
{
uintNetmask = cidr == 0 ? 0 : 0xffffffff << (32 - cidr);
return;
}
BigInteger mask = new BigInteger(new byte[] {
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0x00
});
BigInteger masked = cidr == 0 ? 0 : mask << (128 - cidr);
byte[] m = masked.ToByteArray();
byte[] bmask = new byte[17];
int copy = m.Length > 16 ? 16 : m.Length;
Array.Copy(m, 0, bmask, 0, copy);
uintNetmask = new BigInteger(bmask);
}
#endregion
#region ToCidr
/// <summary>
/// Convert netmask to CIDR
/// 255.255.255.0 -> 24
/// 255.255.0.0 -> 16
/// 255.0.0.0 -> 8
/// </summary>
/// <param name="netmask"></param>
/// <returns></returns>
private static byte ToCidr(BigInteger netmask, AddressFamily family)
{
byte? cidr = null;
IPNetwork.InternalToCidr(false, netmask, family, out cidr);
return (byte)cidr;
}
/// <summary>
/// Convert netmask to CIDR
/// 255.255.255.0 -> 24
/// 255.255.0.0 -> 16
/// 255.0.0.0 -> 8
/// </summary>
/// <param name="netmask"></param>
/// <returns></returns>
private static void InternalToCidr(bool tryParse, BigInteger netmask, AddressFamily family, out byte? cidr)
{
if (!IPNetwork.ValidNetmask(netmask, family))
{
if (tryParse == false)
{
throw new ArgumentException("netmask");
}
cidr = null;
return;
}
byte cidr2 = IPNetwork.BitsSet(netmask, family);
cidr = cidr2;
return;
}
/// <summary>
/// Convert netmask to CIDR
/// 255.255.255.0 -> 24
/// 255.255.0.0 -> 16
/// 255.0.0.0 -> 8
/// </summary>
/// <param name="netmask"></param>
/// <returns></returns>
public static byte ToCidr(IPAddress netmask)
{
byte? cidr = null;
IPNetwork.InternalToCidr(false, netmask, out cidr);
return (byte)cidr;
}
/// <summary>
/// Convert netmask to CIDR
/// 255.255.255.0 -> 24
/// 255.255.0.0 -> 16
/// 255.0.0.0 -> 8
/// </summary>
/// <param name="netmask"></param>
/// <returns></returns>
public static bool TryToCidr(IPAddress netmask, out byte? cidr)
{
byte? cidr2 = null;
IPNetwork.InternalToCidr(true, netmask, out cidr2);
bool parsed = (cidr2 != null);
cidr = cidr2;
return parsed;
}
private static void InternalToCidr(bool tryParse, IPAddress netmask, out byte? cidr)
{
if (netmask == null)
{
if (tryParse == false)
{
throw new ArgumentNullException("netmask");
}
cidr = null;
return;
}
BigInteger? uintNetmask2 = null;
bool parsed = IPNetwork.TryToBigInteger(netmask, out uintNetmask2);
if (parsed == false)
{
if (tryParse == false)
{
throw new ArgumentException("netmask");
}
cidr = null;
return;
}
BigInteger uintNetmask = (BigInteger)uintNetmask2;
byte? cidr2 = null;
IPNetwork.InternalToCidr(tryParse, uintNetmask, netmask.AddressFamily, out cidr2);
cidr = cidr2;
return;
}
#endregion
#region ToNetmask
/// <summary>
/// Convert CIDR to netmask
/// 24 -> 255.255.255.0
/// 16 -> 255.255.0.0
/// 8 -> 255.0.0.0
/// </summary>
/// <see cref="path_to_url"/>
/// <param name="cidr"></param>
/// <returns></returns>
public static IPAddress ToNetmask(byte cidr, AddressFamily family)
{
IPAddress netmask = null;
IPNetwork.InternalToNetmask(false, cidr, family, out netmask);
return netmask;
}
/// <summary>
/// Convert CIDR to netmask
/// 24 -> 255.255.255.0
/// 16 -> 255.255.0.0
/// 8 -> 255.0.0.0
/// </summary>
/// <see cref="path_to_url"/>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TryToNetmask(byte cidr, AddressFamily family, out IPAddress netmask)
{
IPAddress netmask2 = null;
IPNetwork.InternalToNetmask(true, cidr, family, out netmask2);
bool parsed = (netmask2 != null);
netmask = netmask2;
return parsed;
}
private static void InternalToNetmask(bool tryParse, byte cidr, AddressFamily family, out IPAddress netmask)
{
if (family != AddressFamily.InterNetwork
&& family != AddressFamily.InterNetworkV6)
{
if (tryParse == false)
{
throw new ArgumentException("family");
}
netmask = null;
return;
}
if (cidr < 0)
{
if (tryParse == false)
{
throw new ArgumentOutOfRangeException("cidr");
}
netmask = null;
return;
}
int maxCidr = family == AddressFamily.InterNetwork ? 32 : 128;
if (cidr > maxCidr)
{
if (tryParse == false)
{
throw new ArgumentOutOfRangeException("cidr");
}
netmask = null;
return;
}
BigInteger mask = IPNetwork.ToUint(cidr, family);
IPAddress netmask2 = IPNetwork.ToIPAddress(mask, family);
netmask = netmask2;
return;
}
#endregion
#endregion
#region utils
#region BitsSet
/// <summary>
/// Count bits set to 1 in netmask
/// </summary>
/// <see cref="path_to_url"/>
/// <param name="netmask"></param>
/// <returns></returns>
private static byte BitsSet(BigInteger netmask, AddressFamily family)
{
string s = netmask.ToBinaryString();
return (byte)s.Replace("0", "")
.ToCharArray()
.Length;
}
static BigInteger BigMask(byte b, int length)
{
var bytes = new List<byte>(length + 1);
for (int i = 0; i < length; i++)
{
bytes.Add(b);
}
bytes.Add(0);
return new BigInteger(bytes.ToArray());
}
/// <summary>
/// Count bits set to 1 in netmask
/// </summary>
/// <param name="netmask"></param>
/// <returns></returns>
public static uint BitsSet(IPAddress netmask)
{
BigInteger uintNetmask = IPNetwork.ToBigInteger(netmask);
uint bits = IPNetwork.BitsSet(uintNetmask, netmask.AddressFamily);
return bits;
}
#endregion
#region ValidNetmask
/// <summary>
/// return true if netmask is a valid netmask
/// 255.255.255.0, 255.0.0.0, 255.255.240.0, ...
/// </summary>
/// <see cref="path_to_url"/>
/// <param name="netmask"></param>
/// <returns></returns>
public static bool ValidNetmask(IPAddress netmask)
{
if (netmask == null)
{
throw new ArgumentNullException("netmask");
}
BigInteger uintNetmask = IPNetwork.ToBigInteger(netmask);
bool valid = IPNetwork.ValidNetmask(uintNetmask, netmask.AddressFamily);
return valid;
}
private static bool ValidNetmask(BigInteger netmask, AddressFamily family)
{
if (family != AddressFamily.InterNetwork
&& family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException("family");
}
var mask = family == AddressFamily.InterNetwork
? new BigInteger(0x0ffffffff)
: new BigInteger(new byte[]{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0x00
});
BigInteger neg = ((~netmask) & (mask));
bool isNetmask = ((neg + 1) & neg) == 0;
return isNetmask;
}
#endregion
#region ToIPAddress
/// <summary>
/// Transform a uint ipaddress into IPAddress object
/// </summary>
/// <param name="ipaddress"></param>
/// <returns></returns>
public static IPAddress ToIPAddress(BigInteger ipaddress, AddressFamily family)
{
int width = family == AddressFamily.InterNetwork ? 4 : 16;
byte[] bytes = ipaddress.ToByteArray();
byte[] bytes2 = new byte[width];
int copy = bytes.Length > width ? width : bytes.Length;
Array.Copy(bytes, 0, bytes2, 0, copy);
Array.Reverse(bytes2);
byte[] sized = Resize(bytes2, family);
IPAddress ip = new IPAddress(sized);
return ip;
}
private static byte[] Resize(byte[] bytes, AddressFamily family)
{
if (family != AddressFamily.InterNetwork
&& family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException("family");
}
int width = family == AddressFamily.InterNetwork ? 4 : 16;
if (bytes.Length > width)
{
throw new ArgumentException("bytes");
}
byte[] result = new byte[width];
Array.Copy(bytes, 0, result, 0, bytes.Length);
return result;
}
#endregion
#endregion
#region contains
/// <summary>
/// return true if ipaddress is contained in network
/// </summary>
/// <param name="network"></param>
/// <param name="ipaddress"></param>
/// <returns></returns>
public static bool Contains(IPNetwork network, IPAddress ipaddress, bool usableSpace = false)
{
if (network == null)
{
throw new ArgumentNullException("network");
}
if (ipaddress == null)
{
throw new ArgumentNullException("ipaddress");
}
BigInteger uintNetwork = network._network;
BigInteger uintBroadcast = network._broadcast;
BigInteger uintAddress = ToBigInteger(ipaddress);
bool contains = usableSpace == true ?
(uintAddress > uintNetwork && uintAddress < uintBroadcast) :
(uintAddress >= uintNetwork && uintAddress <= uintBroadcast);
return contains;
}
/// <summary>
/// return true is network2 is fully contained in network
/// </summary>
/// <param name="network"></param>
/// <param name="network2"></param>
/// <returns></returns>
public static bool Contains(IPNetwork network, IPNetwork network2)
{
if (network == null)
{
throw new ArgumentNullException("network");
}
if (network2 == null)
{
throw new ArgumentNullException("network2");
}
BigInteger uintNetwork = network._network;
BigInteger uintBroadcast = network._broadcast;
BigInteger uintFirst = network2._network;
BigInteger uintLast = network2._broadcast;
bool contains = (uintFirst >= uintNetwork
&& uintLast <= uintBroadcast);
return contains;
}
#endregion
#region overlap
/// <summary>
/// return true is network2 overlap network
/// </summary>
/// <param name="network"></param>
/// <param name="network2"></param>
/// <returns></returns>
public static bool Overlap(IPNetwork network, IPNetwork network2)
{
if (network == null)
{
throw new ArgumentNullException("network");
}
if (network2 == null)
{
throw new ArgumentNullException("network2");
}
BigInteger uintNetwork = network._network;
BigInteger uintBroadcast = network._broadcast;
BigInteger uintFirst = network2._network;
BigInteger uintLast = network2._broadcast;
bool overlap =
(uintFirst >= uintNetwork && uintFirst <= uintBroadcast)
|| (uintLast >= uintNetwork && uintLast <= uintBroadcast)
|| (uintFirst <= uintNetwork && uintLast >= uintBroadcast)
|| (uintFirst >= uintNetwork && uintLast <= uintBroadcast);
return overlap;
}
#endregion
#region ToString
public override string ToString()
{
return string.Format("{0}/{1}", this.Network, this.Cidr);
}
#endregion
#region IANA block
private static IPNetwork _iana_ablock_reserved;
private static IPNetwork _iana_bblock_reserved;
private static IPNetwork _iana_cblock_reserved;
/// <summary>
/// 10.0.0.0/8
/// </summary>
/// <returns></returns>
public static IPNetwork IANA_ABLK_RESERVED1
{
get
{
if (_iana_ablock_reserved == null)
{
_iana_ablock_reserved = IPNetwork.Parse("10.0.0.0/8");
}
return _iana_ablock_reserved;
}
}
/// <summary>
/// 172.12.0.0/12
/// </summary>
/// <returns></returns>
public static IPNetwork IANA_BBLK_RESERVED1
{
get
{
if (_iana_bblock_reserved == null)
{
_iana_bblock_reserved = IPNetwork.Parse("172.16.0.0/12");
}
return _iana_bblock_reserved;
}
}
/// <summary>
/// 192.168.0.0/16
/// </summary>
/// <returns></returns>
public static IPNetwork IANA_CBLK_RESERVED1
{
get
{
if (_iana_cblock_reserved == null)
{
_iana_cblock_reserved = IPNetwork.Parse("192.168.0.0/16");
}
return _iana_cblock_reserved;
}
}
/// <summary>
/// return true if ipaddress is contained in
/// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
/// </summary>
/// <param name="ipaddress"></param>
/// <returns></returns>
public static bool IsIANAReserved(IPAddress ipaddress)
{
if (ipaddress == null)
{
throw new ArgumentNullException("ipaddress");
}
return IPNetwork.Contains(IPNetwork.IANA_ABLK_RESERVED1, ipaddress)
|| IPNetwork.Contains(IPNetwork.IANA_BBLK_RESERVED1, ipaddress)
|| IPNetwork.Contains(IPNetwork.IANA_CBLK_RESERVED1, ipaddress);
}
/// <summary>
/// return true if ipnetwork is contained in
/// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
/// </summary>
/// <param name="ipnetwork"></param>
/// <returns></returns>
public static bool IsIANAReserved(IPNetwork ipnetwork)
{
if (ipnetwork == null)
{
throw new ArgumentNullException("ipnetwork");
}
return IPNetwork.Contains(IPNetwork.IANA_ABLK_RESERVED1, ipnetwork)
|| IPNetwork.Contains(IPNetwork.IANA_BBLK_RESERVED1, ipnetwork)
|| IPNetwork.Contains(IPNetwork.IANA_CBLK_RESERVED1, ipnetwork);
}
#endregion
#region Subnet
/// <summary>
/// Subnet a network into multiple nets of cidr mask
/// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
/// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
/// </summary>
/// <param name="ipnetwork"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static IPNetworkCollection Subnet(IPNetwork network, byte cidr)
{
IPNetworkCollection ipnetworkCollection = null;
IPNetwork.InternalSubnet(false, network, cidr, out ipnetworkCollection);
return ipnetworkCollection;
}
/// <summary>
/// Subnet a network into multiple nets of cidr mask
/// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
/// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
/// </summary>
/// <param name="ipnetwork"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TrySubnet(IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
{
IPNetworkCollection inc = null;
IPNetwork.InternalSubnet(true, network, cidr, out inc);
if (inc == null)
{
ipnetworkCollection = null;
return false;
}
ipnetworkCollection = inc;
return true;
}
private static void InternalSubnet(bool trySubnet, IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
{
if (network == null)
{
if (trySubnet == false)
{
throw new ArgumentNullException("network");
}
ipnetworkCollection = null;
return;
}
int maxCidr = network._family == AddressFamily.InterNetwork ? 32 : 128;
if (cidr > maxCidr)
{
if (trySubnet == false)
{
throw new ArgumentOutOfRangeException("cidr");
}
ipnetworkCollection = null;
return;
}
if (cidr < network.Cidr)
{
if (trySubnet == false)
{
throw new ArgumentException("cidr");
}
ipnetworkCollection = null;
return;
}
ipnetworkCollection = new IPNetworkCollection(network, cidr);
return;
}
#endregion
#region Supernet
/// <summary>
/// Supernet two consecutive cidr equal subnet into a single one
/// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
/// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
/// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
/// </summary>
/// <param name="network1"></param>
/// <param name="network2"></param>
/// <returns></returns>
public static IPNetwork Supernet(IPNetwork network1, IPNetwork network2)
{
IPNetwork supernet = null;
IPNetwork.InternalSupernet(false, network1, network2, out supernet);
return supernet;
}
/// <summary>
/// Try to supernet two consecutive cidr equal subnet into a single one
/// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
/// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
/// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
/// </summary>
/// <param name="network1"></param>
/// <param name="network2"></param>
/// <returns></returns>
public static bool TrySupernet(IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
{
IPNetwork outSupernet = null;
IPNetwork.InternalSupernet(true, network1, network2, out outSupernet);
bool parsed = (outSupernet != null);
supernet = outSupernet;
return parsed;
}
private static void InternalSupernet(bool trySupernet, IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
{
if (network1 == null)
{
if (trySupernet == false)
{
throw new ArgumentNullException("network1");
}
supernet = null;
return;
}
if (network2 == null)
{
if (trySupernet == false)
{
throw new ArgumentNullException("network2");
}
supernet = null;
return;
}
if (IPNetwork.Contains(network1, network2))
{
supernet = new IPNetwork(network1._network, network1._family, network1.Cidr);
return;
}
if (IPNetwork.Contains(network2, network1))
{
supernet = new IPNetwork(network2._network, network2._family, network2.Cidr);
return;
}
if (network1._cidr != network2._cidr)
{
if (trySupernet == false)
{
throw new ArgumentException("cidr");
}
supernet = null;
return;
}
IPNetwork first = (network1._network < network2._network) ? network1 : network2;
IPNetwork last = (network1._network > network2._network) ? network1 : network2;
/// Starting from here :
/// network1 and network2 have the same cidr,
/// network1 does not contain network2,
/// network2 does not contain network1,
/// first is the lower subnet
/// last is the higher subnet
if ((first._broadcast + 1) != last._network)
{
if (trySupernet == false)
{
throw new ArgumentOutOfRangeException("network");
}
supernet = null;
return;
}
BigInteger uintSupernet = first._network;
byte cidrSupernet = (byte)(first._cidr - 1);
IPNetwork networkSupernet = new IPNetwork(uintSupernet, first._family, cidrSupernet);
if (networkSupernet._network != first._network)
{
if (trySupernet == false)
{
throw new ArgumentException("network");
}
supernet = null;
return;
}
supernet = networkSupernet;
return;
}
#endregion
#region GetHashCode
public override int GetHashCode()
{
return string.Format("{0}|{1}|{2}",
this._ipaddress.GetHashCode(),
this._network.GetHashCode(),
this._cidr.GetHashCode()).GetHashCode();
}
#endregion
#region SupernetArray
/// <summary>
/// Supernet a list of subnet
/// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
/// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
/// </summary>
/// <param name="ipnetworks"></param>
/// <param name="supernet"></param>
/// <returns></returns>
public static IPNetwork[] Supernet(IPNetwork[] ipnetworks)
{
IPNetwork[] supernet;
InternalSupernet(false, ipnetworks, out supernet);
return supernet;
}
/// <summary>
/// Supernet a list of subnet
/// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
/// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
/// </summary>
/// <param name="ipnetworks"></param>
/// <param name="supernet"></param>
/// <returns></returns>
public static bool TrySupernet(IPNetwork[] ipnetworks, out IPNetwork[] supernet)
{
bool supernetted = InternalSupernet(true, ipnetworks, out supernet);
return supernetted;
}
public static bool InternalSupernet(bool trySupernet, IPNetwork[] ipnetworks, out IPNetwork[] supernet)
{
if (ipnetworks == null)
{
if (trySupernet == false)
{
throw new ArgumentNullException("ipnetworks");
}
supernet = null;
return false;
}
if (ipnetworks.Length <= 0)
{
supernet = new IPNetwork[0];
return true;
}
List<IPNetwork> supernetted = new List<IPNetwork>();
List<IPNetwork> ipns = IPNetwork.Array2List(ipnetworks);
Stack<IPNetwork> current = IPNetwork.List2Stack(ipns);
int previousCount = 0;
int currentCount = current.Count;
while (previousCount != currentCount)
{
supernetted.Clear();
while (current.Count > 1)
{
IPNetwork ipn1 = current.Pop();
IPNetwork ipn2 = current.Peek();
IPNetwork outNetwork = null;
bool success = IPNetwork.TrySupernet(ipn1, ipn2, out outNetwork);
if (success)
{
current.Pop();
current.Push(outNetwork);
}
else
{
supernetted.Add(ipn1);
}
}
if (current.Count == 1)
{
supernetted.Add(current.Pop());
}
previousCount = currentCount;
currentCount = supernetted.Count;
current = IPNetwork.List2Stack(supernetted);
}
supernet = supernetted.ToArray();
return true;
}
private static Stack<IPNetwork> List2Stack(List<IPNetwork> list)
{
Stack<IPNetwork> stack = new Stack<IPNetwork>();
list.ForEach(new Action<IPNetwork>(
delegate (IPNetwork ipn)
{
stack.Push(ipn);
}
));
return stack;
}
private static List<IPNetwork> Array2List(IPNetwork[] array)
{
List<IPNetwork> ipns = new List<IPNetwork>();
ipns.AddRange(array);
IPNetwork.RemoveNull(ipns);
ipns.Sort(new Comparison<IPNetwork>(
delegate (IPNetwork ipn1, IPNetwork ipn2)
{
int networkCompare = ipn1._network.CompareTo(ipn2._network);
if (networkCompare == 0)
{
int cidrCompare = ipn1._cidr.CompareTo(ipn2._cidr);
return cidrCompare;
}
return networkCompare;
}
));
ipns.Reverse();
return ipns;
}
private static void RemoveNull(List<IPNetwork> ipns)
{
ipns.RemoveAll(new Predicate<IPNetwork>(
delegate (IPNetwork ipn)
{
if (ipn == null)
{
return true;
}
return false;
}
));
}
#endregion
#region WideSubnet
public static IPNetwork WideSubnet(string start, string end)
{
if (string.IsNullOrEmpty(start))
{
throw new ArgumentNullException("start");
}
if (string.IsNullOrEmpty(end))
{
throw new ArgumentNullException("end");
}
IPAddress startIP;
if (!IPAddress.TryParse(start, out startIP))
{
throw new ArgumentException("start");
}
IPAddress endIP;
if (!IPAddress.TryParse(end, out endIP))
{
throw new ArgumentException("end");
}
if (startIP.AddressFamily != endIP.AddressFamily)
{
throw new NotSupportedException("MixedAddressFamily");
}
IPNetwork ipnetwork = new IPNetwork(0, startIP.AddressFamily, 0);
for (byte cidr = 32; cidr >= 0; cidr--)
{
IPNetwork wideSubnet = IPNetwork.Parse(start, cidr);
if (IPNetwork.Contains(wideSubnet, endIP))
{
ipnetwork = wideSubnet;
break;
}
}
return ipnetwork;
}
public static bool TryWideSubnet(IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
{
IPNetwork ipn = null;
IPNetwork.InternalWideSubnet(true, ipnetworks, out ipn);
if (ipn == null)
{
ipnetwork = null;
return false;
}
ipnetwork = ipn;
return true;
}
public static IPNetwork WideSubnet(IPNetwork[] ipnetworks)
{
IPNetwork ipn = null;
IPNetwork.InternalWideSubnet(false, ipnetworks, out ipn);
return ipn;
}
private static void InternalWideSubnet(bool tryWide, IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
{
if (ipnetworks == null)
{
if (tryWide == false)
{
throw new ArgumentNullException("ipnetworks");
}
ipnetwork = null;
return;
}
IPNetwork[] nnin = Array.FindAll<IPNetwork>(ipnetworks, new Predicate<IPNetwork>(
delegate (IPNetwork ipnet)
{
return ipnet != null;
}
));
if (nnin.Length <= 0)
{
if (tryWide == false)
{
throw new ArgumentException("ipnetworks");
}
ipnetwork = null;
return;
}
if (nnin.Length == 1)
{
IPNetwork ipn0 = nnin[0];
ipnetwork = ipn0;
return;
}
Array.Sort<IPNetwork>(nnin);
IPNetwork nnin0 = nnin[0];
BigInteger uintNnin0 = nnin0._ipaddress;
IPNetwork nninX = nnin[nnin.Length - 1];
IPAddress ipaddressX = nninX.Broadcast;
AddressFamily family = ipnetworks[0]._family;
foreach (var ipnx in ipnetworks)
{
if (ipnx._family != family)
{
throw new ArgumentException("MixedAddressFamily");
}
}
IPNetwork ipn = new IPNetwork(0, family, 0);
for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
{
IPNetwork wideSubnet = new IPNetwork(uintNnin0, family, cidr);
if (IPNetwork.Contains(wideSubnet, ipaddressX))
{
ipn = wideSubnet;
break;
}
}
ipnetwork = ipn;
return;
}
#endregion
#region Print
/// <summary>
/// Print an ipnetwork in a clear representation string
/// </summary>
/// <param name="ipnetwork"></param>
/// <returns></returns>
public static string Print(IPNetwork ipnetwork)
{
if (ipnetwork == null)
{
throw new ArgumentNullException("ipnetwork");
}
StringWriter sw = new StringWriter();
sw.WriteLine("IPNetwork : {0}", ipnetwork.ToString());
sw.WriteLine("Network : {0}", ipnetwork.Network);
sw.WriteLine("Netmask : {0}", ipnetwork.Netmask);
sw.WriteLine("Cidr : {0}", ipnetwork.Cidr);
sw.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
sw.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
sw.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
sw.WriteLine("Usable : {0}", ipnetwork.Usable);
return sw.ToString();
}
#endregion
#region TryGuessCidr
/// <summary>
///
/// Class Leading bits Default netmask
/// A (CIDR /8) 00 255.0.0.0
/// A (CIDR /8) 01 255.0.0.0
/// B (CIDR /16) 10 255.255.0.0
/// C (CIDR /24) 11 255.255.255.0
///
/// </summary>
/// <param name="ip"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TryGuessCidr(string ip, out byte cidr)
{
IPAddress ipaddress = null;
bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
if (parsed == false)
{
cidr = 0;
return false;
}
if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
{
cidr = 64;
return true;
}
BigInteger uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
uintIPAddress = uintIPAddress >> 29;
if (uintIPAddress <= 3)
{
cidr = 8;
return true;
}
else if (uintIPAddress <= 5)
{
cidr = 16;
return true;
}
else if (uintIPAddress <= 6)
{
cidr = 24;
return true;
}
cidr = 0;
return false;
}
/// <summary>
/// Try to parse cidr. Have to be >= 0 and <= 32 or 128
/// </summary>
/// <param name="sidr"></param>
/// <param name="cidr"></param>
/// <returns></returns>
public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
{
byte b = 0;
if (!byte.TryParse(sidr, out b))
{
cidr = null;
return false;
}
IPAddress netmask = null;
if (!IPNetwork.TryToNetmask(b, family, out netmask))
{
cidr = null;
return false;
}
cidr = b;
return true;
}
#endregion
#region Increment
public IPNetwork Increment()
{
var netInt = ToBigInteger(Network);
netInt += Total;
var addressInt = ToBigInteger(IpAddress);
addressInt += Total;
var net = Parse(ToIPAddress(netInt, AddressFamily), Netmask);
var address = Parse(ToIPAddress(addressInt, IpAddress.AddressFamily), Netmask).IpAddress;
net.IpAddress = address;
return net;
}
#endregion
#region Increment
public IPNetwork Decrement()
{
var netInt = ToBigInteger(Network);
netInt -= Total;
var addressInt = ToBigInteger(IpAddress);
addressInt -= Total;
var net = Parse(ToIPAddress(netInt, AddressFamily), Netmask);
var address = Parse(ToIPAddress(addressInt, IpAddress.AddressFamily), Netmask).IpAddress;
net.IpAddress = address;
return net;
}
#endregion
#region ListIPAddress
public static IPAddressCollection ListIPAddress(IPNetwork ipnetwork)
{
return new IPAddressCollection(ipnetwork);
}
#endregion
/**
* Need a better way to do it
*
#region TrySubstractNetwork
public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
if (ipnetworks == null) {
result = null;
return false;
}
if (ipnetworks.Length <= 0) {
result = null;
return false;
}
if (substract == null) {
result = null;
return false;
}
var results = new List<IPNetwork>();
foreach (var ipn in ipnetworks) {
if (!Overlap(ipn, substract)) {
results.Add(ipn);
continue;
}
var collection = IPNetwork.Subnet(ipn, substract.Cidr);
var rtemp = new List<IPNetwork>();
foreach(var subnet in collection) {
if (subnet != substract) {
rtemp.Add(subnet);
}
}
var supernets = Supernet(rtemp.ToArray());
results.AddRange(supernets);
}
result = results;
return true;
}
#endregion
* **/
#region IComparable<IPNetwork> Members
public static Int32 Compare(IPNetwork left, IPNetwork right)
{
// two null IPNetworks are equal
if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
// two same IPNetworks are equal
if (ReferenceEquals(left, right)) return 0;
// null is always sorted first
if (ReferenceEquals(left, null)) return -1;
if (ReferenceEquals(right, null)) return 1;
// first test the network
var result = left._network.CompareTo(right._network);
if (result != 0) return result;
// then test the cidr
result = left._cidr.CompareTo(right._cidr);
return result;
}
public Int32 CompareTo(IPNetwork other)
{
return Compare(this, other);
}
public Int32 CompareTo(Object obj)
{
// null is at less
if (obj == null) return 1;
// convert to a proper Cidr object
var other = obj as IPNetwork;
// type problem if null
if (other == null)
{
throw new ArgumentException(
"The supplied parameter is an invalid type. Please supply an IPNetwork type.",
"obj");
}
// perform the comparision
return CompareTo(other);
}
#endregion
#region IEquatable<IPNetwork> Members
public static Boolean Equals(IPNetwork left, IPNetwork right)
{
return Compare(left, right) == 0;
}
public Boolean Equals(IPNetwork other)
{
return Equals(this, other);
}
public override Boolean Equals(Object obj)
{
return Equals(this, obj as IPNetwork);
}
#endregion
#region Operators
public static Boolean operator ==(IPNetwork left, IPNetwork right)
{
return Equals(left, right);
}
public static Boolean operator !=(IPNetwork left, IPNetwork right)
{
return !Equals(left, right);
}
public static Boolean operator <(IPNetwork left, IPNetwork right)
{
return Compare(left, right) < 0;
}
public static Boolean operator >(IPNetwork left, IPNetwork right)
{
return Compare(left, right) > 0;
}
#endregion
}
}
``` | /content/code_sandbox/LabXml/Network/IPNetwork Class/IPNetwork.cs | smalltalk | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 13,995 |
```css
*{
color: #ffffff;
font-family: "Source Sans Pro";
font-style: normal;
font-weight: normal ;
line-height: 105px;
text-align: center;
}
``` | /content/code_sandbox/fastlane/appstoreres/assets/styles/style.css | css | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 45 |
```json
PODS:
- AppCenter (4.4.3):
- AppCenter/Analytics (= 4.4.3)
- AppCenter/Crashes (= 4.4.3)
- AppCenter/Analytics (4.4.3):
- AppCenter/Core
- AppCenter/Core (4.4.3)
- AppCenter/Crashes (4.4.3):
- AppCenter/Core
- AppCenter/Distribute (4.4.3):
- AppCenter/Core
- Gridicons (0.19)
- Simperium (1.9.0):
- Simperium/DiffMatchPach (= 1.9.0)
- Simperium/JRSwizzle (= 1.9.0)
- Simperium/SocketTrust (= 1.9.0)
- Simperium/SPReachability (= 1.9.0)
- Simperium/SSKeychain (= 1.9.0)
- Simperium/DiffMatchPach (1.9.0)
- Simperium/JRSwizzle (1.9.0)
- Simperium/SocketTrust (1.9.0)
- Simperium/SPReachability (1.9.0)
- Simperium/SSKeychain (1.9.0)
- SwiftLint (0.54.0)
- WordPress-Ratings-iOS (0.0.2)
- ZIPFoundation (0.9.15)
DEPENDENCIES:
- AppCenter (~> 4.4.3)
- AppCenter/Distribute (~> 4.4.3)
- Gridicons (~> 0.18)
- Simperium (= 1.9.0)
- SwiftLint (= 0.54.0)
- WordPress-Ratings-iOS (= 0.0.2)
- ZIPFoundation (~> 0.9.9)
SPEC REPOS:
trunk:
- AppCenter
- Gridicons
- Simperium
- SwiftLint
- WordPress-Ratings-iOS
- ZIPFoundation
SPEC CHECKSUMS:
AppCenter: 3fd04aa1b166e16fdb03ec81dabe488aece83fbd
Gridicons: dc92efbe5fd60111d2e8ea051d84a60cca552abc
Simperium: 45d828d68aad71f3449371346f270013943eff78
SwiftLint: c1de071d9d08c8aba837545f6254315bc900e211
WordPress-Ratings-iOS: 9f83dbba6e728c5121b1fd21b5683cf2fd120646
ZIPFoundation: 063163dc828bf699c5be160eb4f58f676322d94f
PODFILE CHECKSUM: 6fc187e283b4fb7f9f4a0ef73a27632724c90845
COCOAPODS: 1.15.2
``` | /content/code_sandbox/Podfile.lock | json | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 684 |
```yaml
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2024-02-20 18:18:24 UTC using RuboCop version 1.60.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 2
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: Max, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns.
# URISchemes: http, https
Layout/LineLength:
Exclude:
- 'fastlane/Fastfile'
# Offense count: 6
# Configuration parameters: AllowedMethods.
# AllowedMethods: enums
Lint/ConstantDefinitionInBlock:
Exclude:
- 'fastlane/Fastfile'
# Offense count: 2
Lint/NonLocalExitFromIterator:
Exclude:
- 'Scripts/update-translations.rb'
# Offense count: 1
# Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames.
# AllowedNames: as, at, by, cc, db, id, if, in, io, ip, of, on, os, pp, to
Naming/MethodParameterName:
Exclude:
- 'Scripts/update-translations.rb'
# Offense count: 9
# Configuration parameters: AllowedVariables.
Style/GlobalVars:
Exclude:
- 'fastlane/Fastfile'
``` | /content/code_sandbox/.rubocop_todo.yml | yaml | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 355 |
```ruby
# frozen_string_literal: true
require 'dotenv'
# TODO: It would be nice to decouple this from Fastlane.
# To give a good UX in the current use case, however, it's best to access the Fastlane UI methods directly.
require 'fastlane'
# Manages loading of environment variables from a .env and accessing them in a user-friendly way.
class EnvManager
@env_path = nil
@env_example_path = nil
@print_error_lambda = nil
# Set up by loading the .env file with the given name.
#
# TODO: We could go one step and guess the name based on the repo URL.
def self.set_up(
env_file_name:,
env_file_folder: File.join(Dir.home, '.a8c-apps'),
example_env_file_path: 'fastlane/example.env',
print_error_lambda: ->(message) { FastlaneCore::UI.user_error!(message) }
)
@env_path = File.join(env_file_folder, env_file_name)
@env_example_path = example_env_file_path
@print_error_lambda = print_error_lambda
# We don't check for @env_path to exist here
Dotenv.load(@env_path)
end
# Use this instead of getting values from `ENV` directly. It will throw an error if the requested value is missing or empty.
def self.get_required_env!(key)
unless ENV.key?(key)
message = "Environment variable '#{key}' is not set."
if running_on_ci?
@print_error_lambda.call(message)
elsif File.exist?(@env_path)
@print_error_lambda.call("#{message} Consider adding it to #{@env_path}.")
else
env_file_dir = File.dirname(@env_path)
env_file_name = File.basename(@env_path)
@print_error_lambda.call <<~MSG
#{env_file_name} not found in #{env_file_dir} while looking for env var #{key}.
Please copy #{@env_example_path} to #{@env_path} and fill in the value for #{key}.
mkdir -p #{env_file_dir} && cp #{@env_example_path} #{@env_path}
MSG
end
end
value = ENV.fetch(key)
UI.user_error!("Env var for key #{key} is set but empty. Please set a value for #{key}.") if value.to_s.empty?
value
end
# Use this to ensure all env vars a lane requires are set.
#
# The best place to call this is at the start of a lane, to fail early.
def self.require_env_vars!(*keys)
keys.each { |key| get_required_env!(key) }
end
def self.running_on_ci?
ENV['CI'] == 'true'
end
end
``` | /content/code_sandbox/fastlane/lib/env_manager.rb | ruby | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 605 |
```yaml
inherit_from: .rubocop_todo.yml
AllCops:
Exclude:
- DerivedData/**/*
- Pods/**/*
- vendor/**/*
NewCops: enable
SuggestExtensions:
rubocop-rake: false
Metrics/MethodLength:
Max: 30
Layout/LineLength:
Max: 180
Metrics/BlockLength:
Exclude: &xfiles
- fastlane/Fastfile
- fastlane/lanes/*.rb
- Rakefile
Style/HashSyntax:
EnforcedShorthandSyntax: never
# Used by UI test account methods. See path_to_url for more details.
Style/GlobalVars:
AllowedVariables:
- $used_test_account_index
``` | /content/code_sandbox/.rubocop.yml | yaml | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 158 |
```yaml
swiftlint_version: 0.54.0
# Project configuration
excluded:
- Pods
- fastlane
- vendor
# Rules
only_rules:
# Colons should be next to the identifier when specifying a type.
- colon
# There should be no space before and one after any comma.
- comma
# if,for,while,do statements shouldn't wrap their conditionals in parentheses.
- control_statement
- discarded_notification_center_observer
- duplicate_imports
# Arguments can be omitted when matching enums with associated types if they
# are not used.
- empty_enum_arguments
# Prefer `() -> ` over `Void -> `.
- empty_parameters
# MARK comment should be in valid format.
- mark
# Opening braces should be preceded by a single space and on the same line as
# the declaration.
- opening_brace
# Files should have a single trailing newline.
- trailing_newline
# Lines should not have trailing semicolons.
- trailing_semicolon
# Lines should not have trailing whitespace.
# - trailing_whitespace
# - vertical_whitespace
- custom_rules
# Rules configuration
control_statement:
severity: error
custom_rules:
natural_content_alignment:
name: "Natural Content Alignment"
regex: '\.contentHorizontalAlignment(\s*)=(\s*)(\.left|\.right)'
message: "Forcing content alignment left or right can affect the Right-to-Left layout. Use naturalContentHorizontalAlignment instead."
severity: warning
natural_text_alignment:
name: "Natural Text Alignment"
regex: '\.textAlignment(\s*)=(\s*).left'
message: "Forcing text alignment to left can affect the Right-to-Left layout. Consider setting it to `natural`"
severity: warning
inverse_text_alignment:
name: "Inverse Text Alignment"
regex: '\.textAlignment(\s*)=(\s*).right'
message: "When forcing text alignment to the right, be sure to handle the Right-to-Left layout case properly, and then silence this warning with this line `// swiftlint:disable:next inverse_text_alignment`"
severity: warning
localization_comment:
name: "Localization Comment"
regex: 'NSLocalizedString([^,]+,\s+comment:\s*"")'
message: "Localized strings should include a description giving context for how the string is used."
severity: warning
string_interpolation_in_localized_string:
name: "String Interpolation in Localized String"
regex: 'NSLocalizedString\("[^"]*\\\(\S*\)'
message: "Localized strings must not use interpolated variables. Instead, use `String(format:`"
severity: error
``` | /content/code_sandbox/.swiftlint.yml | yaml | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 597 |
```ruby
# frozen_string_literal: true
APP_STORE_CONNECT_OUTPUT_NAME = 'Simplenote-AppStore'
XCARCHIVE_PATH = File.join(OUTPUT_DIRECTORY_PATH, "#{APP_STORE_CONNECT_OUTPUT_NAME}.xcarchive")
XCARCHIVE_ZIP_PATH = File.join(OUTPUT_DIRECTORY_PATH, "#{APP_STORE_CONNECT_OUTPUT_NAME}.xcarchive.zip")
lane :build_for_app_store_connect do |fetch_code_signing: true|
appstore_code_signing if fetch_code_signing
build_app(
scheme: 'Simplenote',
workspace: WORKSPACE,
configuration: 'Distribution AppStore',
clean: true,
export_method: 'app-store',
# The options below might seem redundant but are currently all necessary to have predictable artifact paths to use in other lanes.
#
# - archive_path sets the full path for the xcarchive.
# - output_directory and output_name set the path and basename for the ipa and dSYM.
#
# We could have used 'build_path: OUTPUT_DIRECTORY_PATH' for the xcarchive...
# ...but doing so would append a timestamp and unnecessarily complicate other logic to get the path
archive_path: XCARCHIVE_PATH,
output_directory: OUTPUT_DIRECTORY_PATH,
output_name: APP_STORE_CONNECT_OUTPUT_NAME
)
# It's convenient to have a ZIP available for things like CI uploads
UI.message("Zipping #{XCARCHIVE_PATH} to #{XCARCHIVE_ZIP_PATH}...")
zip(path: XCARCHIVE_PATH, output_path: XCARCHIVE_ZIP_PATH)
end
lane :upload_to_app_store_connect do |beta_release:, skip_prechecks: false, create_release: false|
sentry_check_cli_installed unless skip_prechecks
ipa_path = File.join(OUTPUT_DIRECTORY_PATH, "#{APP_STORE_CONNECT_OUTPUT_NAME}.ipa")
UI.user_error!("Could not find ipa at #{ipa_path}!") unless File.exist?(ipa_path)
dsym_path = File.join(OUTPUT_DIRECTORY_PATH, "#{APP_STORE_CONNECT_OUTPUT_NAME}.app.dSYM.zip")
UI.user_error!("Could not find dSYM at #{dsym_path}!") unless File.exist?(ipa_path)
UI.important("Uploading ipa at #{ipa_path} to TestFlight...")
upload_to_testflight(
ipa: ipa_path,
api_key_path: APP_STORE_CONNECT_KEY_PATH,
skip_waiting_for_build_processing: false,
distribute_external: true,
changelog: RELEASE_NOTES_SOURCE_PATH,
reject_build_waiting_for_review: true,
groups: ['Internal A8C Beta Testers', 'External Beta Testers']
)
UI.important("Uploading dSYM at #{dsym_path} to Sentry...")
sentry_upload_dsym(
dsym_path: dsym_path,
auth_token: EnvManager.get_required_env!('SENTRY_AUTH_TOKEN'),
org_slug: 'a8c',
project_slug: 'simplenote-ios'
)
next unless create_release
version = beta_release ? build_code_current : release_version_current
create_release(
repository: GITHUB_REPO,
version: version,
release_notes_file_path: File.join(PROJECT_ROOT_FOLDER, 'Simplenote', 'Resources', 'release_notes.txt'),
release_assets: XCARCHIVE_ZIP_PATH.to_s,
prerelease: beta_release
)
end
``` | /content/code_sandbox/fastlane/lanes/build.rb | ruby | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 711 |
```ruby
# frozen_string_literal: true
# List of locales used for the app strings (GlotPress code => `*.lproj` folder name`)
#
# TODO: Replace with `LocaleHelper` once provided by release toolkit (path_to_url
GLOTPRESS_TO_LPROJ_APP_LOCALE_CODES = {
'ar' => 'ar', # Arabic
'cy' => 'cy', # Welsh
'de' => 'de', # German
'el' => 'el', # Greek
'es' => 'es', # Spanish
'fa' => 'fa', # Persian
'fr' => 'fr', # French
'he' => 'he', # Hebrew
'id' => 'id', # Indonesian
'it' => 'it', # Italian
'ja' => 'ja', # Japanese
'ko' => 'ko', # Korean
'nl' => 'nl', # Dutch
'pt-br' => 'pt-BR', # Portuguese (Brazil)
'ru' => 'ru', # Russian
'sv' => 'sv', # Swedish
'tr' => 'tr', # Turkish
'zh-cn' => 'zh-Hans-CN', # Chinese (China)
'zh-tw' => 'zh-Hant-TW' # Chinese (Taiwan)
}.freeze
# Mapping of all locales which can be used for AppStore metadata (Glotpress code => AppStore Connect code)
#
# TODO: Replace with `LocaleHelper` once provided by release toolkit (path_to_url
GLOTPRESS_TO_ASC_METADATA_LOCALE_CODES = {
'ar' => 'ar-SA',
'de' => 'de-DE',
'es' => 'es-ES',
'fr' => 'fr-FR',
'he' => 'he',
'id' => 'id',
'it' => 'it',
'ja' => 'ja',
'ko' => 'ko',
'nl' => 'nl-NL',
'pt-br' => 'pt-BR',
'ru' => 'ru',
'sv' => 'sv',
'tr' => 'tr',
'zh-cn' => 'zh-Hans',
'zh-tw' => 'zh-Hant'
}.freeze
platform :ios do
desc 'Updates the main `Localizable.strings` file that will be imported by GlotPress'
lane :generate_strings_file_for_glotpress do
en_lproj_path = File.join(PROJECT_ROOT_FOLDER, 'Simplenote', 'en.lproj')
ios_generate_strings_file_from_code(
paths: [
'Simplenote/',
'SimplenoteIntents/',
'SimplenoteShare/',
'SimplenoteWidgets/',
'Pods/Simperium/Simperium/',
'Pods/Simperium/Simperium-iOS'
],
output_dir: en_lproj_path
)
git_commit(
path: en_lproj_path,
message: 'Freeze strings for localization',
allow_nothing_to_commit: true
)
end
lane :download_localized_strings_and_metadata_from_glotpress do
download_localized_strings_from_glotpress
download_localized_metadata_from_glotpress
end
lane :download_localized_strings_from_glotpress do
parent_dir_for_lprojs = File.join(PROJECT_ROOT_FOLDER, 'Simplenote')
ios_download_strings_files_from_glotpress(
project_url: GLOTPRESS_APP_STRINGS_PROJECT_URL,
locales: GLOTPRESS_TO_LPROJ_APP_LOCALE_CODES,
download_dir: parent_dir_for_lprojs
)
git_commit(
path: File.join(parent_dir_for_lprojs, '*.lproj', 'Localizable.strings'),
message: 'Update app translations `Localizable.strings`',
allow_nothing_to_commit: true
)
end
lane :download_localized_metadata_from_glotpress do
# FIXME: We should make the `fastlane/metadata/default/release_notes.txt` path be the source of truth for the original copies in the future.
# (will require changes in the `update_appstore_strings` lane, the Release Scenario, the MC tool to generate the announcement post)
#
# In the meantime, just copy the file to the right place for `deliver` to find, for the `default` pseudo-locale which is used as fallback
FileUtils.cp(RELEASE_NOTES_SOURCE_PATH, File.join(STORE_METADATA_FOLDER, 'default', 'release_notes.txt'))
# FIXME: Replace this with a call to the future replacement of `gp_downloadmetadata` once it's implemented in the release-toolkit (see paaHJt-31O-p2).
target_files = {
"v#{release_version_current}-whats-new": { desc: 'release_notes.txt', max_size: 4000 },
app_store_name: { desc: 'name.txt', max_size: 30 },
app_store_subtitle: { desc: 'subtitle.txt', max_size: 30 },
app_store_desc: { desc: 'description.txt', max_size: 4000 },
app_store_keywords: { desc: 'keywords.txt', max_size: 100 }
}
gp_downloadmetadata(
project_url: GLOTPRESS_STORE_METADATA_PROJECT_URL,
target_files: target_files,
locales: GLOTPRESS_TO_ASC_METADATA_LOCALE_CODES,
download_path: STORE_METADATA_FOLDER
)
files_to_commit = [File.join(STORE_METADATA_FOLDER, '**', '*.txt')]
ensure_default_metadata_are_not_overridden(metadata_files_hash: target_files)
files_to_commit.append(*generate_gitkeep_for_empty_locale_folders)
git_add(path: files_to_commit, shell_escape: false)
git_commit(
path: files_to_commit,
message: 'Update App Store metadata translations',
allow_nothing_to_commit: true
)
sanitize_appstore_keywords
end
# TODO: This ought to be part of the localized metadata download action, or of Fastlane itself.
desc 'Updates the files with the localized keywords values for App Store Connect to match the 100 characters requirement'
lane :sanitize_appstore_keywords do
Dir[File.join(STORE_METADATA_FOLDER, '**')].each do |locale_dir|
keywords_path = File.join(locale_dir, 'keywords.txt')
unless File.exist?(keywords_path)
UI.important "Could not find keywords file in #{locale_dir}. Skipping..."
next
end
keywords = File.read(keywords_path)
app_store_connect_keywords_length_limit = 100
if keywords.length <= app_store_connect_keywords_length_limit
UI.success "#{keywords_path} has less than #{app_store_connect_keywords_length_limit} characters."
next
end
UI.important "#{keywords_path} has more than #{app_store_connect_keywords_length_limit} characters. Trimming it..."
english_comma = ','
arabic_comma = ''
locale_code = File.basename(locale_dir)
keywords = keywords.gsub(arabic_comma, english_comma) if locale_code == 'ar-SA'
keywords = keywords.split(english_comma)[0...-1].join(english_comma) until keywords.length <= app_store_connect_keywords_length_limit
File.write(keywords_path, keywords)
git_commit(
path: keywords_path,
message: "Trim #{locale_code} keywords to be less than #{app_store_connect_keywords_length_limit} characters",
allow_nothing_to_commit: false
)
end
end
end
# Ensure that none of the `.txt` files in `en-US` would accidentally override our originals in `default`
def ensure_default_metadata_are_not_overridden(metadata_files_hash:)
metadata_files_hash.values.map { |t| t[:desc] }.each do |file|
en_file_path = File.join(STORE_METADATA_FOLDER, 'en-US', file)
override_not_allowed_message = <<~MSG
File `#{en_file_path}` would override the same one in `#{STORE_METADATA_FOLDER}/default`.
`default/` is the source of truth and we cannot allow it to change unintentionally.
Delete `#{en_file_path}`, ensure the version in `default/` has the expected original copy, and try again.
MSG
UI.user_error!(override_not_allowed_message) if File.exist?(en_file_path)
end
lane :lint_localizations do
ios_lint_localizations(input_dir: APP_RESOURCES_DIR, allow_retry: true)
end
end
# Ensure even empty locale folders have an empty `.gitkeep` file.
# This way, if we don't have any translation ready for those locales, we'll still have the folders in Git for clarity.
def generate_gitkeep_for_empty_locale_folders
gitkeeps = []
GLOTPRESS_TO_ASC_METADATA_LOCALE_CODES.each_value do |locale|
gitkeep = File.join(STORE_METADATA_FOLDER, locale, '.gitkeep')
next if File.exist?(gitkeep)
FileUtils.mkdir_p(File.dirname(gitkeep))
FileUtils.touch(gitkeep)
gitkeeps.append(gitkeep)
end
gitkeeps
end
``` | /content/code_sandbox/fastlane/lanes/localization.rb | ruby | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 2,000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.