/// <summary> /// Queries for instance and invokes an instance method /// </summary> /// <param name="query">Query parameters</param> /// <param name="methodInvocationInfo">Method invocation details</param> /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the object instance being operated on</param> public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) { _parentJob.DisableFlowControlForPendingJobsQueue(); ThrottlingJob closureOverParentJob = _parentJob; SwitchParameter closureOverAsJob = this.AsJob; foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) { StartableJob queryJob = this.DoCreateQueryJob( sessionForJob, query, delegate (TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) { StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob( sessionForMethodInvocationJob, objectInstance, methodInvocationInfo, passThru, closureOverAsJob.IsPresent); if (methodInvocationJob != null) { closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); } }); if (queryJob != null) { if (!this.AsJob.IsPresent) { _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } else { _parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } } } }
protected override void BeginProcessing() { string warning = String.Format(Properties.Resources.DeprecatedCmdlet_F2, CmdletName, @"PowerShell's built-in Microsoft.PowerShell.Management\Start-Process cmdlet"); WriteWarning(warning); if (WildcardPattern.ContainsWildcardCharacters(_fileName)) { ErrorHandler.ThrowIllegalCharsInPath(_fileName); } if (_credentials != null) { // If using credentials, NoShellExecute must be set to true _noShellExecute = true; } if (_workingDir == null) { _workingDir = SessionState.Path.CurrentFileSystemLocation.Path; } }
protected override void ExecuteCmdlet() { if (SelectedWeb.IsNoScriptSite()) { ThrowTerminatingError(new ErrorRecord(new Exception("Site has NoScript enabled, and setting property bag values is not supported"), "NoScriptEnabled", ErrorCategory.InvalidOperation, this)); return; } if (!MyInvocation.BoundParameters.ContainsKey("Folder")) { if (!Indexed) { // If it is already an indexed property we still have to add it back to the indexed properties Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key)); } SelectedWeb.SetPropertyBagValue(Key, Value); if (Indexed) { SelectedWeb.AddIndexedPropertyBagKey(Key); } else { SelectedWeb.RemoveIndexedPropertyBagKey(Key); } } else { SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder); var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl); folder.EnsureProperty(f => f.Properties); folder.Properties[Key] = Value; folder.Update(); ClientContext.ExecuteQueryRetry(); } }
internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { string localhostComputerName; DebugHelper.WriteLogEx(); IEnumerable <string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } CimSessionProxy cimSessionProxyTestConnection = new CimSessionProxyTestConnection(computerName, sessionOptions); if (computerName == ConstValue.NullComputerName) { localhostComputerName = ConstValue.LocalhostComputerName; } else { localhostComputerName = computerName; } string str = localhostComputerName; CimSessionWrapper cimSessionWrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, str, cimSessionProxyTestConnection.CimSession, cimSessionProxyTestConnection.Protocol); CimNewSession.CimTestCimSessionContext cimTestCimSessionContext = new CimNewSession.CimTestCimSessionContext(cimSessionProxyTestConnection, cimSessionWrapper); cimSessionProxyTestConnection.ContextObject = cimTestCimSessionContext; SwitchParameter skipTestConnection = cmdlet.SkipTestConnection; if (!skipTestConnection.IsPresent) { this.cimTestSession.TestCimSession(computerName, cimSessionProxyTestConnection); } else { this.AddSessionToCache(cimSessionProxyTestConnection.CimSession, cimTestCimSessionContext, new CmdletOperationBase(cmdlet)); } } }
private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { using (ClearHistoryCommand._trace.TraceMethod()) { if (cmdline == null) { if (id > 0L) { HistoryInfo entry = this.history.GetEntry(id); if (entry == null || entry.Id != id) { this.WriteError(new ErrorRecord((Exception) new ArgumentException(ResourceManagerCache.FormatResourceString("History", "NoHistoryForId", (object)id)), "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, (object)id)); } this.entries = this.history.GetEntries(id, (long)count, newest); } else { this.entries = this.history.GetEntries(0L, (long)count, newest); } } else { WildcardPattern wildcardpattern = new WildcardPattern(cmdline, WildcardOptions.IgnoreCase); if (!this._countParamterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline)) { count = 0; } this.entries = this.history.GetEntries(wildcardpattern, (long)count, newest); } foreach (HistoryInfo entry in this.entries) { if (entry != null && !entry.Cleared) { this.history.ClearEntry(entry.Id); } } } }
private bool RemoveADClaimTypeCmdletValidationCSRoutine() { string[] strArrays; SwitchParameter force = this._cmdletParameters.Force; if (!force.ToBool()) { ADClaimType identity = this._cmdletParameters.Identity; object attributeValueFromObjectName = AttributeConverters.GetAttributeValueFromObjectName <ADClaimTypeFactory <ADClaimType>, ADClaimType>(identity, this.GetDefaultPartitionPath(), "msDS-ClaimSharesPossibleValuesWithBL", "msDS-ClaimSharesPossibleValuesWithBL", this.GetCmdletSessionInfo()); if (attributeValueFromObjectName != null) { string str = attributeValueFromObjectName as string; if (str == null) { strArrays = attributeValueFromObjectName as string[]; } else { string[] strArrays1 = new string[1]; strArrays1[0] = str; strArrays = strArrays1; } object[] identifyingString = new object[1]; identifyingString[0] = identity.IdentifyingString; string str1 = string.Format(CultureInfo.CurrentCulture, StringResources.RemoveClaimTypeSharesValueWithError, identifyingString); if (strArrays != null) { for (int i = 0; i < 5 && i < (int)strArrays.Length; i++) { str1 = string.Concat(str1, Environment.NewLine, strArrays[i]); } } base.WriteError(new ErrorRecord(new ADException(str1), "RemoveADClaimType:RemoveADClaimTypeCmdletValidationCSRoutine", ErrorCategory.InvalidData, null)); return(false); } } return(true); }
protected override void InternalValidate() { ((IConfigurationSession)base.DataSession).SessionSettings.IsSharedConfigChecked = true; if (!this.IgnoreDehydratedFlag) { SharedConfigurationTaskHelper.VerifyIsNotTinyTenant(base.CurrentOrgState, new Task.ErrorLoggerDelegate(base.WriteError)); } base.InternalValidate(); if (base.HasErrors) { return; } if (this.IsDefault) { this.DataObject.IsDefault = true; QueryFilter additionalFilter = new ComparisonFilter(ComparisonOperator.NotEqual, ADObjectSchema.Guid, this.DataObject.Id.ObjectGuid); this.otherDefaultPolicies = DefaultTeamMailboxProvisioningPolicyUtility.GetDefaultPolicies((IConfigurationSession)base.DataSession, additionalFilter); if (this.otherDefaultPolicies.Count > 0) { this.updateOtherDefaultPolicies = true; } } }
private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { if (cmdline == null) { if (id > 0L) { HistoryInfo entry = this.history.GetEntry(id); if ((entry == null) || (entry.Id != id)) { Exception exception = new ArgumentException(StringUtil.Format(HistoryStrings.NoHistoryForId, id)); base.WriteError(new ErrorRecord(exception, "GetHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, id)); } this.entries = this.history.GetEntries(id, (long)count, newest); } else { this.entries = this.history.GetEntries((long)0L, (long)count, newest); } } else { WildcardPattern wildcardpattern = new WildcardPattern(cmdline, WildcardOptions.IgnoreCase); if (!this._countParamterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline)) { count = 0; } this.entries = this.history.GetEntries(wildcardpattern, (long)count, newest); } foreach (HistoryInfo info2 in this.entries) { if ((info2 != null) && !info2.Cleared) { this.history.ClearEntry(info2.Id); } } }
bool ShowConfirm(string title, string text) { var args = new MessageArgs() { Text = text, Caption = title, Options = MessageOptions.LeftAligned, Buttons = new string[] { "Step", "Continue", "Cancel" }, Position = new Point(int.MaxValue, 1) }; switch (Far.Api.Message(args)) { case 0: return(true); case 1: Confirm = false; return(true); default: return(false); } }
// Incremental Zone Transfer // // Get the current SOA, modify the serial and send the request. internal void IXFRLookup(String Name, UInt32 Serial, String Server) { this.Tcp = false; Lookup(Name, RecordType.SOA, Server, false); // Use the server returned by the SOA as a target for the query DnsPacket Message = (DnsPacket)ResponseMessages[0]; SOA SOARecord = new SOA(Name, Serial); Header DnsHeader = new Header(false, 1); DnsHeader.AuthorityCount = 1; Question DnsQuestion = new Question(Name, RecordType.IXFR); Byte[] Payload = CreatePayload(DnsHeader, DnsQuestion); Payload = AddAuthority(Payload, SOARecord); // Clear old responses ResponseMessages.Clear(); this.Tcp = true; ExecuteLookup(Payload, RecordType.IXFR, Server, true); }
protected override ADServerSettings GetCmdletADServerSettings() { PropertyBag fields = base.CurrentTaskContext.InvocationInfo.Fields; SwitchParameter switchParameter = fields.Contains("IsDatacenter") ? ((SwitchParameter)fields["IsDatacenter"]) : new SwitchParameter(false); bool flag = fields.Contains("DomainController"); OrganizationIdParameter organizationIdParameter = (OrganizationIdParameter)fields["PrimaryOrganization"]; PartitionId partitionId = (organizationIdParameter != null) ? ADAccountPartitionLocator.GetPartitionIdByAcceptedDomainName(organizationIdParameter.RawIdentity) : null; string value = null; ADServerSettings serverSettings = ExchangePropertyContainer.GetServerSettings(base.CurrentTaskContext.SessionState); if (serverSettings != null && partitionId != null) { value = serverSettings.PreferredGlobalCatalog(partitionId.ForestFQDN); } if (switchParameter && organizationIdParameter != null && string.IsNullOrEmpty(value) && partitionId != null && !flag) { if (this.domainBasedADServerSettings == null) { this.domainBasedADServerSettings = RunspaceServerSettings.CreateGcOnlyRunspaceServerSettings(organizationIdParameter.RawIdentity.ToLowerInvariant(), partitionId.ForestFQDN, false); } return(this.domainBasedADServerSettings); } return(base.GetCmdletADServerSettings()); }
protected override void BeginProcessing() { if (base.ParameterSetName == "ScriptBlockSet") { Dictionary <string, object> boundParameters = base.MyInvocation.BoundParameters; if (boundParameters != null) { SwitchParameter parameter = false; SwitchParameter parameter2 = false; if (boundParameters.ContainsKey("whatif")) { parameter = (SwitchParameter)boundParameters["whatif"]; } if (boundParameters.ContainsKey("confirm")) { parameter2 = (SwitchParameter)boundParameters["confirm"]; } if ((parameter != false) || (parameter2 != false)) { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(InternalCommandStrings.NoShouldProcessForScriptBlockSet), "NoShouldProcessForScriptBlockSet", ErrorCategory.InvalidOperation, null); base.ThrowTerminatingError(errorRecord); } } this.end = this.scripts.Count; this.start = (this.scripts.Count > 1) ? 1 : 0; if (!this.setEndScript && (this.scripts.Count > 2)) { this.end = this.scripts.Count - 1; this.endScript = this.scripts[this.end]; } if ((this.end >= 2) && (this.scripts[0] != null)) { this.scripts[0].InvokeUsingCmdlet(this, false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, new object[0], AutomationNull.Value, new object[0]); } } }
public IEnumerable <PSResourceInfo> FindByResourceName( string[] name, ResourceType type, string version, SwitchParameter prerelease, string[] tag, string[] repository, PSCredential credential, SwitchParameter includeDependencies) { _type = type; _version = version; _prerelease = prerelease; _tag = tag; _credential = credential; _includeDependencies = includeDependencies; Dbg.Assert(name.Length != 0, "Name length cannot be 0"); _pkgsLeftToFind = name.ToList(); List <PSRepositoryInfo> repositoriesToSearch; try { repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList); foreach (string error in errorList) { _cmdletPassedIn.WriteError(new ErrorRecord( new PSInvalidOperationException(error), "ErrorGettingSpecifiedRepo", ErrorCategory.InvalidOperation, this)); } } catch (Exception e) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(e.Message), "ErrorLoadingRepositoryStoreFile", ErrorCategory.InvalidArgument, this)); yield break; } // loop through repositoriesToSearch and if PSGallery add it to list with same priority as PSGallery repo for (int i = 0; i < repositoriesToSearch.Count; i++) { if (String.Equals(repositoriesToSearch[i].Name, _psGalleryRepoName, StringComparison.InvariantCultureIgnoreCase)) { // for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*' // detect if Script repository needs to be added and/or Module repository needs to be skipped Uri psGalleryScriptsUrl = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/"); PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUrl, repositoriesToSearch[i].Priority, false); if (_type == ResourceType.None) { _cmdletPassedIn.WriteDebug("Null Type provided, so add PSGalleryScripts repository"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); } else if (_type != ResourceType.None && _type == ResourceType.Script) { _cmdletPassedIn.WriteDebug("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only)"); repositoriesToSearch.Insert(i + 1, psGalleryScripts); repositoriesToSearch.RemoveAt(i); // remove PSGallery } } } for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++) { _cmdletPassedIn.WriteDebug(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name)); foreach (var pkg in SearchFromRepository( repositoryName: repositoriesToSearch[i].Name, repositoryUrl: repositoriesToSearch[i].Url)) { yield return(pkg); } } }
public DriveParams() { PersistentConnection = new SwitchParameter(true); }
public override void ExecuteCmdlet() { this.VM.OSProfile = new OSProfile { ComputerName = this.ComputerName, AdminUsername = this.Credential.UserName, AdminPassword = ConversionUtilities.SecureStringToString(this.Credential.Password), CustomData = string.IsNullOrWhiteSpace(this.CustomData) ? null : Convert.ToBase64String(Encoding.UTF8.GetBytes(this.CustomData)), }; if (this.ParameterSetName == LinuxParamSet) { if (this.VM.OSProfile.WindowsConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } if (this.VM.OSProfile.LinuxConfiguration == null) { this.VM.OSProfile.LinuxConfiguration = new LinuxConfiguration(); } this.VM.OSProfile.LinuxConfiguration.DisablePasswordAuthentication = (this.DisablePasswordAuthentication.IsPresent) ? (bool?)true : null; } else { if (this.VM.OSProfile.LinuxConfiguration != null) { throw new ArgumentException(Microsoft.Azure.Commands.Compute.Properties.Resources.BothWindowsAndLinuxConfigurationsSpecified); } if (this.VM.OSProfile.WindowsConfiguration == null) { this.VM.OSProfile.WindowsConfiguration = new WindowsConfiguration(); this.VM.OSProfile.WindowsConfiguration.AdditionalUnattendContent = null; } var listenerList = new List <WinRMListener>(); if (this.WinRMHttp.IsPresent) { listenerList.Add(new WinRMListener { Protocol = ProtocolTypes.Http, CertificateUrl = null, }); } if (this.WinRMHttps.IsPresent) { listenerList.Add(new WinRMListener { Protocol = ProtocolTypes.Https, CertificateUrl = this.WinRMCertificateUrl.ToString(), }); } // OS Profile this.VM.OSProfile.WindowsConfiguration.ProvisionVMAgent = this.ProvisionVMAgent.IsPresent; this.VM.OSProfile.WindowsConfiguration.EnableAutomaticUpdates = this.EnableAutoUpdate.IsPresent; this.VM.OSProfile.WindowsConfiguration.TimeZone = this.TimeZone; this.VM.OSProfile.WindowsConfiguration.WinRM = !(this.WinRMHttp.IsPresent || this.WinRMHttps.IsPresent) ? null : new WinRMConfiguration { Listeners = listenerList, }; } WriteObject(this.VM); }
protected override void InternalValidate() { base.InternalValidate(); if (base.HasErrors) { return; } if (Datacenter.IsMicrosoftHostedOnly(false)) { List <RetentionPolicy> allRetentionPolicies = AdPolicyReader.GetAllRetentionPolicies(this.ConfigurationSession, base.OrganizationId); if (allRetentionPolicies.Count >= 100) { base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorTenantRetentionPolicyLimitReached(100)), ErrorCategory.InvalidOperation, this.DataObject); } } if (this.IsDefault && this.IsDefaultArbitrationMailbox) { base.WriteError(new ArgumentException(Strings.ErrorMultipleDefaultRetentionPolicy), ErrorCategory.InvalidArgument, this.DataObject.Identity); } if (!this.IgnoreDehydratedFlag && SharedConfiguration.IsDehydratedConfiguration(base.CurrentOrganizationId)) { base.WriteError(new ArgumentException(Strings.ErrorWriteOpOnDehydratedTenant), ErrorCategory.InvalidArgument, this.DataObject.Identity); } if (this.IsDefault && this.IsDefaultArbitrationMailbox) { base.WriteError(new ArgumentException(Strings.ErrorMultipleDefaultRetentionPolicy), ErrorCategory.InvalidArgument, this.DataObject.Identity); } if (this.IsDefault) { this.DataObject.IsDefault = true; this.existingDefaultPolicies = RetentionPolicyUtility.GetDefaultPolicies((IConfigurationSession)base.DataSession, false); } else if (this.IsDefaultArbitrationMailbox) { this.DataObject.IsDefaultArbitrationMailbox = true; this.existingDefaultPolicies = RetentionPolicyUtility.GetDefaultPolicies((IConfigurationSession)base.DataSession, true); } if (this.existingDefaultPolicies != null && this.existingDefaultPolicies.Count > 0) { this.updateExistingDefaultPolicies = true; } if (this.RetentionPolicyTagLinks != null) { this.DataObject.RetentionPolicyTagLinks.Clear(); PresentationRetentionPolicyTag[] array = (from x in (from x in this.RetentionPolicyTagLinks select(RetentionPolicyTag) base.GetDataObject <RetentionPolicyTag>(x, base.DataSession, null, new LocalizedString?(Strings.ErrorRetentionTagNotFound(x.ToString())), new LocalizedString?(Strings.ErrorAmbiguousRetentionPolicyTagId(x.ToString())))).Distinct(new ADObjectComparer <RetentionPolicyTag>()) select new PresentationRetentionPolicyTag(x)).ToArray <PresentationRetentionPolicyTag>(); RetentionPolicyValidator.ValicateDefaultTags(this.DataObject, array, new Task.TaskErrorLoggingDelegate(base.WriteError)); RetentionPolicyValidator.ValidateSystemFolderTags(this.DataObject, array, new Task.TaskErrorLoggingDelegate(base.WriteError)); array.ForEach(delegate(PresentationRetentionPolicyTag x) { this.DataObject.RetentionPolicyTagLinks.Add(x.Id); }); } if (base.Fields.Contains("RetentionId")) { this.DataObject.RetentionId = this.RetentionId; string policyName; if (!(base.DataSession as IConfigurationSession).CheckForRetentionPolicyWithConflictingRetentionId(this.DataObject.RetentionId, out policyName)) { base.WriteError(new RetentionPolicyTagTaskException(Strings.ErrorRetentionIdConflictsWithRetentionPolicy(this.DataObject.RetentionId.ToString(), policyName)), ErrorCategory.InvalidOperation, this.DataObject); } } }
public static void CommandLineParser(ref object obj, string[] args) { Type type; PropertyInfo[] objProps; ConfigurationBuilder configBuilder = new ConfigurationBuilder(); type = obj.GetType(); objProps = type.GetProperties(); ArgumentAttribute orphanAttribute = null; PropertyInfo orphanPropInfo = null; if (objProps != null) { for (int i = 0; i < args.Length; i++) { PropertyInfo propInfo; Object[] customParams; int propLoc = i; bool isAssigned = false; for (int j = 0; j < objProps.Length; j++) { propInfo = objProps[j]; customParams = propInfo.GetCustomAttributes(typeof(ArgumentAttribute), false); if (customParams != null && customParams.Length > 0) { ArgumentAttribute param = customParams[0] as ArgumentAttribute; try { if (param != null && (param.ShortNotation == args[i] || param.FullName.ToLower() == args[i].ToLower() || param.ShortNotation2 == args[i] || param.FullName2.ToLower() == args[i].ToLower())) { if (propInfo.PropertyType.FullName == "System.Boolean" || propInfo.PropertyType.FullName == "System.Management.Automation.SwitchParameter") { bool value = false; if (propInfo.PropertyType.FullName == "System.Management.Automation.SwitchParameter") { object objvalue = param.DefaultValue; value = Convert.ToBoolean(objvalue); objvalue = !value; SwitchParameter paramSwitch = new SwitchParameter(!value); propInfo.SetValue(obj, paramSwitch, null); isAssigned = true; break; } else { value = (bool)param.DefaultValue; if (value) { propInfo.SetValue(obj, false, null); } else { propInfo.SetValue(obj, true, null); } isAssigned = true; } break; } else { int index = i + 1; if (index <= (args.Length - 1)) { object value; if (propInfo.PropertyType.FullName.Contains((new CacheTopologyParam()).GetType().ToString())) { value = GetTopologyType(args[++i]); } else if (propInfo.PropertyType.FullName.Contains((new ReplicationStrategyParam()).GetType().ToString())) { value = GetReplicatedStrategy(args[++i]); } else if (propInfo.PropertyType.FullName.Contains((new EvictionPolicyParam()).GetType().ToString())) { value = GetEvictinPolicy(args[++i]); } else { value = configBuilder.ConvertToPrimitive(propInfo.PropertyType, args[++i], null); } if (propInfo.PropertyType.IsAssignableFrom(value.GetType())) { propInfo.SetValue(obj, value, null); isAssigned = true; break; } } } } else if (param != null && ((string.IsNullOrEmpty(param.ShortNotation) && string.IsNullOrEmpty(param.FullName)) || (string.IsNullOrEmpty(param.ShortNotation2) && string.IsNullOrEmpty(param.FullName2)))) { if (orphanAttribute == null && !isAssigned) { orphanAttribute = param; orphanPropInfo = propInfo; } } } catch (Exception e) { throw new Exception("Can not set the value for attribute " + param.ShortNotation + " Error :" + e.Message.ToString()); } } } if (!isAssigned) { if (orphanAttribute != null && orphanPropInfo != null) { if (orphanPropInfo.GetValue(obj, null) != null) { object value = configBuilder.ConvertToPrimitive(orphanPropInfo.PropertyType, args[i], null); if (orphanPropInfo.PropertyType.IsAssignableFrom(value.GetType())) { orphanPropInfo.SetValue(obj, value, null); } } } } } } }
internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { this.ReallocateBufferIfNeeded(); if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if (((count == -1L) || (count > this._countEntriesAdded)) || (count > this._countEntriesInBuffer)) { count = this._countEntriesInBuffer; } if ((count == 0L) || (this._countEntriesInBuffer == 0)) { return(new HistoryInfo[0]); } lock (this._syncRoot) { ArrayList list = new ArrayList(); if (id > 0L) { long num; long num2 = id; if (!newest.IsPresent) { num = (num2 - count) + 1L; if (num < 1L) { num = 1L; } for (long i = num2; i >= num; i -= 1L) { if (num <= 1L) { break; } if ((this._buffer[this.GetIndexFromId(i)] != null) && this._buffer[this.GetIndexFromId(i)].Cleared) { num -= 1L; } } for (long j = num; j <= num2; j += 1L) { if ((this._buffer[this.GetIndexFromId(j)] != null) && !this._buffer[this.GetIndexFromId(j)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(j)].Clone()); } } } else { num = (num2 + count) - 1L; if (num >= this._countEntriesAdded) { num = this._countEntriesAdded; } for (long k = num2; k <= num; k += 1L) { if (num >= this._countEntriesAdded) { break; } if ((this._buffer[this.GetIndexFromId(k)] != null) && this._buffer[this.GetIndexFromId(k)].Cleared) { num += 1L; } } for (long m = num; m >= num2; m -= 1L) { if ((this._buffer[this.GetIndexFromId(m)] != null) && !this._buffer[this.GetIndexFromId(m)].Cleared) { list.Add(this._buffer[this.GetIndexFromId(m)].Clone()); } } } } else { long num7; long num8 = 0L; if (this._capacity != 0x1000) { num8 = this.SmallestIDinBuffer(); } if (!newest.IsPresent) { num7 = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { num7 = num8; } long num9 = count - 1L; while (num9 >= 0L) { if (num7 > this._countEntriesAdded) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 += 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num9 -= 1L; num7 += 1L; } } } else { num7 = this._countEntriesAdded; long num10 = count - 1L; while (num10 >= 0L) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num7 < num8)) || (num7 < 1L)) { break; } if (((num7 <= 0L) || (this.GetIndexFromId(num7) >= this._buffer.Length)) || this._buffer[this.GetIndexFromId(num7)].Cleared) { num7 -= 1L; } else { list.Add(this._buffer[this.GetIndexFromId(num7)].Clone()); num10 -= 1L; num7 -= 1L; } } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return(array); } }
public SendBugReportCmdlet() { IncludeCommandHistory = SwitchParameter.Present; IncludeErrorHistory = SwitchParameter.Present; }
private void Run() { if (this.IsParameterBound(c => c.ComputerNamePrefix)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.ComputerNamePrefix = this.ComputerNamePrefix; } if (this.IsParameterBound(c => c.AdminUsername)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminUsername = this.AdminUsername; } if (this.IsParameterBound(c => c.AdminPassword)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminPassword = this.AdminPassword; } if (this.IsParameterBound(c => c.CustomData)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.CustomData = this.CustomData; } if (this.IsParameterBound(c => c.WindowsConfigurationProvisionVMAgent)) { if (this.IsParameterBound(c => c.LinuxConfigurationProvisionVMAgent)) { throw new Exception("Please provide only one of the following parameters: -WindowsConfigurationProvisionVMAgent or -LinuxConfigurationProvisionVMAgent"); } // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.WindowsConfigurationProvisionVMAgent; } if (this.IsParameterBound(c => c.LinuxConfigurationProvisionVMAgent)) { if (this.IsParameterBound(c => c.WindowsConfigurationProvisionVMAgent)) { throw new Exception("Please provide only one of the following parameters: -WindowsConfigurationProvisionVMAgent or -LinuxConfigurationProvisionVMAgent"); } // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.ProvisionVMAgent = this.LinuxConfigurationProvisionVMAgent; } if (this.IsParameterBound(c => c.WindowsConfigurationEnableAutomaticUpdate)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.WindowsConfigurationEnableAutomaticUpdate; } if (this.IsParameterBound(c => c.TimeZone)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone; } if (this.IsParameterBound(c => c.AdditionalUnattendContent)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.AdditionalUnattendContent = this.AdditionalUnattendContent; } if (this.IsParameterBound(c => c.Listener)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } // WinRM if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM = new WinRMConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM.Listeners = this.Listener; } if (this.IsParameterBound(c => c.LinuxConfigurationDisablePasswordAuthentication)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // LinuxConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.LinuxConfigurationDisablePasswordAuthentication; } if (this.IsParameterBound(c => c.PublicKey)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // LinuxConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } // Ssh if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh = new SshConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh.PublicKeys = this.PublicKey; } if (this.IsParameterBound(c => c.Secret)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.Secrets = this.Secret; } if (this.IsParameterBound(c => c.WindowsConfigurationPatchMode)) { if (this.IsParameterBound(c => c.LinuxConfigurationPatchMode)) { throw new Exception("Please provide only one of the following parameters: -WindowsConfigurationPatchMode or - LinuxConfigurationPatchMode"); } // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } // PatchSettings if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings = new PatchSettings(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings.PatchMode = this.WindowsConfigurationPatchMode; } // EnableHotPatching in PatchSettings if (this.IsParameterBound(c => c.EnableHotpatching)) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } // PatchSettings if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings = new PatchSettings(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.PatchSettings.EnableHotpatching = this.EnableHotpatching; } if (this.IsParameterBound(c => c.LinuxConfigurationPatchMode)) { if (this.IsParameterBound(c => c.WindowsConfigurationPatchMode)) { throw new Exception("Please provide only one of the following parameters: -WindowsConfigurationPatchMode or - LinuxConfigurationPatchMode"); } // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new PSVirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // LinuxConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } // LinuxPatchSettings if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.PatchSettings == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.PatchSettings = new LinuxPatchSettings(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.PatchSettings.PatchMode = this.LinuxConfigurationPatchMode; } WriteObject(this.VirtualMachineScaleSet); }
public void NewPaaSDeploymentProcess() { NewAzureDeploymentCommand.NewAzureDeploymentCommand variable = null; Func <string, Deployment> func = null; Func <string, Uri> func1 = null; Action <string> action = null; Action <string> action1 = null; bool flag = false; using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel)) { try { new List <PersistentVMRoleContext>(); NewAzureDeploymentCommand newAzureDeploymentCommand = this; if (func == null) { func = (string s) => base.Channel.GetDeploymentBySlot(s, this.ServiceName, "Production"); } Deployment deployment = ((CmdletBase <IServiceManagement>)newAzureDeploymentCommand).RetryCall <Deployment>(func); if (deployment.RoleList != null && string.Compare(deployment.RoleList[0].RoleType, "PersistentVMRole", StringComparison.OrdinalIgnoreCase) == 0) { throw new ArgumentException("Cannot Create New Deployment with Virtual Machines Present"); } } catch (CommunicationException communicationException1) { CommunicationException communicationException = communicationException1; if (communicationException as EndpointNotFoundException == null && !base.IsVerbose()) { this.WriteErrorDetails(communicationException); } } } string currentStorageAccount = base.get_CurrentSubscription().get_CurrentStorageAccount(); if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { Uri uri = new Uri(this.Package); } else { ProgressRecord progressRecord = new ProgressRecord(0, "Please wait...", "Uploading package to blob storage"); base.WriteProgress(progressRecord); flag = true; NewAzureDeploymentCommand.NewAzureDeploymentCommand variable1 = variable; NewAzureDeploymentCommand newAzureDeploymentCommand1 = this; if (func1 == null) { func1 = (string s) => AzureBlob.UploadPackageToBlob(base.Channel, currentStorageAccount, s, this.Package); } variable1.packageUrl = ((CmdletBase <IServiceManagement>)newAzureDeploymentCommand1).RetryCall <Uri>(func1); } CreateDeploymentInput createDeploymentInput = new CreateDeploymentInput(); createDeploymentInput.PackageUrl = uri; createDeploymentInput.Configuration = Utility.GetConfiguration(this.Configuration); createDeploymentInput.Label = ServiceManagementHelper.EncodeToBase64String(this.Label); createDeploymentInput.Name = this.Name; SwitchParameter doNotStart = this.DoNotStart; createDeploymentInput.StartDeployment = new bool?(!doNotStart.IsPresent); SwitchParameter treatWarningsAsError = this.TreatWarningsAsError; createDeploymentInput.TreatWarningsAsError = new bool?(treatWarningsAsError.IsPresent); CreateDeploymentInput createDeploymentInput1 = createDeploymentInput; using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel)) { try { ProgressRecord progressRecord1 = new ProgressRecord(0, "Please wait...", "Creating the new deployment"); base.WriteProgress(progressRecord1); CmdletExtensions.WriteVerboseOutputForObject(this, createDeploymentInput1); NewAzureDeploymentCommand newAzureDeploymentCommand2 = this; if (action == null) { action = (string s) => this.Channel.CreateOrUpdateDeployment(s, this.ServiceName, this.Slot, this.deploymentInput); } ((CmdletBase <IServiceManagement>)newAzureDeploymentCommand2).RetryCall(action); Operation operation = base.WaitForOperation(base.CommandRuntime.ToString()); ManagementOperationContext managementOperationContext = new ManagementOperationContext(); managementOperationContext.OperationDescription = base.CommandRuntime.ToString(); managementOperationContext.OperationId = operation.OperationTrackingId; managementOperationContext.OperationStatus = operation.Status; ManagementOperationContext managementOperationContext1 = managementOperationContext; base.WriteObject(managementOperationContext1, true); if (flag) { NewAzureDeploymentCommand newAzureDeploymentCommand3 = this; if (action1 == null) { action1 = (string s) => AzureBlob.DeletePackageFromBlob(base.Channel, currentStorageAccount, s, uri); } ((CmdletBase <IServiceManagement>)newAzureDeploymentCommand3).RetryCall(action1); } } catch (CommunicationException communicationException3) { CommunicationException communicationException2 = communicationException3; this.WriteErrorDetails(communicationException2); } } }
public ProviderRemoveItemDynamicParameters() { this.deleteKey = new SwitchParameter(); }
public WriteCmdlet() { this.Append = false; this.openedExistingFile = false; }
internal static bool TryGetDefaultParameterValue(Type type, out object value) { if (type == typeof(string)) { value = string.Empty; return true; } if (type.GetTypeInfo().IsClass) { value = null; return true; } if (type == typeof(bool)) { value = Boxed.False; return true; } if (type == typeof(SwitchParameter)) { value = new SwitchParameter(false); return true; } if (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(type)) && !type.GetTypeInfo().IsEnum) { value = 0; return true; } value = null; return false; }
internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, SwitchParameter newest) { lock (this._syncRoot) { if (count < -1L) { throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException("newest"); } if ((count > this._countEntriesAdded) || (count == -1L)) { count = this._countEntriesInBuffer; } ArrayList list = new ArrayList(); long num = 1L; if (this._capacity != 0x1000) { num = this.SmallestIDinBuffer(); } if (count != 0L) { if (!newest.IsPresent) { long id = 1L; if ((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) { id = num; } long num3 = 0L; while (num3 <= (count - 1L)) { if (id > this._countEntriesAdded) { break; } if (!this._buffer[this.GetIndexFromId(id)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(id)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(id)].Clone()); num3 += 1L; } id += 1L; } } else { long num4 = this._countEntriesAdded; long num5 = 0L; while (num5 <= (count - 1L)) { if ((((this._capacity != 0x1000) && (this._countEntriesAdded > this._capacity)) && (num4 < num)) || (num4 < 1L)) { break; } if (!this._buffer[this.GetIndexFromId(num4)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(num4)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(num4)].Clone()); num5 += 1L; } num4 -= 1L; } } } else { for (long i = 1L; i <= this._countEntriesAdded; i += 1L) { if (!this._buffer[this.GetIndexFromId(i)].Cleared && wildcardpattern.IsMatch(this._buffer[this.GetIndexFromId(i)].CommandLine.Trim())) { list.Add(this._buffer[this.GetIndexFromId(i)].Clone()); } } } HistoryInfo[] array = new HistoryInfo[list.Count]; list.CopyTo(array); return(array); } }
protected override void ExecuteCmdlet() { #pragma warning disable CS0618 // Type or member is obsolete SourceUrl = SourceUrl ?? ServerRelativeUrl; #pragma warning restore CS0618 // Type or member is obsolete var webServerRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!SourceUrl.StartsWith("/")) { SourceUrl = UrlUtility.Combine(webServerRelativeUrl, SourceUrl); } if (!TargetUrl.StartsWith("/")) { TargetUrl = UrlUtility.Combine(webServerRelativeUrl, TargetUrl); } Uri currentContextUri = new Uri(ClientContext.Url); Uri sourceUri = new Uri(currentContextUri, SourceUrl); Uri sourceWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, sourceUri); Uri targetUri = new Uri(currentContextUri, TargetUrl); Uri targetWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, targetUri); _sourceContext = ClientContext; if (!currentContextUri.AbsoluteUri.Equals(sourceWebUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase)) { _sourceContext = ClientContext.Clone(sourceWebUri); } bool isFile = true; bool srcIsFolder = false; File file = null; Folder folder = null; try { #if ONPREMISES file = _sourceContext.Web.GetFileByServerRelativeUrl(SourceUrl); #else file = _sourceContext.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); #endif file.EnsureProperties(f => f.Name, f => f.Exists); isFile = file.Exists; } catch { isFile = false; } if (!isFile) { #if ONPREMISES folder = _sourceContext.Web.GetFolderByServerRelativeUrl(SourceUrl); #else folder = _sourceContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); #endif #if !SP2013 folder.EnsureProperties(f => f.Name, f => f.Exists); srcIsFolder = folder.Exists; #else folder.EnsureProperties(f => f.Name); try { folder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder srcIsFolder = true; } catch { srcIsFolder = false; } #endif } if (Force || ShouldContinue(string.Format(Resources.CopyFile0To1, SourceUrl, TargetUrl), Resources.Confirm)) { var srcWeb = _sourceContext.Web; srcWeb.EnsureProperty(s => s.Url); _targetContext = ClientContext.Clone(targetWebUri.AbsoluteUri); var dstWeb = _targetContext.Web; dstWeb.EnsureProperties(s => s.Url, s => s.ServerRelativeUrl); if (srcWeb.Url == dstWeb.Url) { try { var targetFile = UrlUtility.Combine(TargetUrl, file?.Name); // If src/dst are on the same Web, then try using CopyTo - backwards compability #if ONPREMISES file?.CopyTo(targetFile, OverwriteIfAlreadyExists); #else file?.CopyToUsingPath(ResourcePath.FromDecodedUrl(targetFile), OverwriteIfAlreadyExists); #endif _sourceContext.ExecuteQueryRetry(); return; } catch { SkipSourceFolderName = true; // target folder exist //swallow exception, in case target was a lib/folder which exists } } //different site/site collection Folder targetFolder = null; string fileOrFolderName = null; bool targetFolderExists = false; try { #if ONPREMISES targetFolder = _targetContext.Web.GetFolderByServerRelativeUrl(TargetUrl); #else targetFolder = _targetContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(TargetUrl)); #endif #if !SP2013 targetFolder.EnsureProperties(f => f.Name, f => f.Exists); if (!targetFolder.Exists) { throw new Exception("TargetUrl is an existing file, not folder"); } targetFolderExists = true; #else targetFolder.EnsureProperties(f => f.Name); try { targetFolder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder targetFolderExists = true; } catch { targetFolderExists = false; } if (!targetFolderExists) { throw new Exception("TargetUrl is an existing file, not folder"); } #endif } catch (Exception) { targetFolder = null; Expression <Func <List, object> > expressionRelativeUrl = l => l.RootFolder.ServerRelativeUrl; var query = _targetContext.Web.Lists.IncludeWithDefaultProperties(expressionRelativeUrl); var lists = _targetContext.LoadQuery(query); _targetContext.ExecuteQueryRetry(); lists = lists.OrderByDescending(l => l.RootFolder.ServerRelativeUrl); // order descending in case more lists start with the same foreach (List targetList in lists) { if (!TargetUrl.StartsWith(targetList.RootFolder.ServerRelativeUrl, StringComparison.InvariantCultureIgnoreCase)) { continue; } fileOrFolderName = Regex.Replace(TargetUrl, _targetContext.Web.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/'); targetFolder = srcIsFolder ? _targetContext.Web.EnsureFolderPath(fileOrFolderName) : targetList.RootFolder; //fileOrFolderName = Regex.Replace(TargetUrl, targetList.RootFolder.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/'); //targetFolder = srcIsFolder ? targetList.RootFolder.EnsureFolder(fileOrFolderName) : targetList.RootFolder; break; } } if (targetFolder == null) { throw new Exception("Target does not exist"); } if (srcIsFolder) { if (!SkipSourceFolderName && targetFolderExists) { targetFolder = targetFolder.EnsureFolder(folder.Name); } CopyFolder(folder, targetFolder); } else { UploadFile(file, targetFolder, fileOrFolderName); } } }
public GetI2CRegister() { this.ByteCount = 1; this.Raw = false; }
/// <summary> /// Resume the Job. /// </summary> protected override void ProcessRecord() { //List of jobs to resume List <Job> jobsToResume = null; switch (ParameterSetName) { case NameParameterSet: { jobsToResume = FindJobsMatchingByName(true, false, true, false); } break; case InstanceIdParameterSet: { jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); } break; case SessionIdParameterSet: { jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); } break; case StateParameterSet: { jobsToResume = FindJobsMatchingByState(false); } break; case FilterParameterSet: { jobsToResume = FindJobsMatchingByFilter(false); } break; default: { jobsToResume = CopyJobsToList(_jobs, false, false); } break; } _allJobsToResume.AddRange(jobsToResume); // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state // Setting Wait to true so that this cmdlet will wait for the running job state. if (_allJobsToResume.Count == 1) { Wait = true; } foreach (Job job in jobsToResume) { var job2 = job as Job2; // If the job is not Job2, the resume operation is not supported. if (job2 == null) { WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); continue; } string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); if (ShouldProcess(targetString, VerbsLifecycle.Resume)) { _cleanUpActions.Add(job2, HandleResumeJobCompleted); job2.ResumeJobCompleted += HandleResumeJobCompleted; lock (_syncObject) { if (!_pendingJobs.Contains(job2.InstanceId)) { _pendingJobs.Add(job2.InstanceId); } } job2.ResumeJobAsync(); } } }
private Collection <WSManConnectionInfo> GetConnectionObjects() { string str; Collection <WSManConnectionInfo> wSManConnectionInfos = new Collection <WSManConnectionInfo>(); if (base.ParameterSetName == "ComputerName" || base.ParameterSetName == "ComputerNameGuid") { SwitchParameter useSSL = this.UseSSL; if (useSSL.IsPresent) { str = "https"; } else { str = "http"; } string str1 = str; string[] computerName = this.ComputerName; for (int i = 0; i < (int)computerName.Length; i++) { string str2 = computerName[i]; WSManConnectionInfo wSManConnectionInfo = new WSManConnectionInfo(); wSManConnectionInfo.Scheme = str1; wSManConnectionInfo.ComputerName = base.ResolveComputerName(str2); wSManConnectionInfo.AppName = this.ApplicationName; wSManConnectionInfo.ShellUri = this.ConfigurationName; wSManConnectionInfo.Port = this.Port; if (this.CertificateThumbprint == null) { wSManConnectionInfo.Credential = this.Credential; } else { wSManConnectionInfo.CertificateThumbprint = this.CertificateThumbprint; } wSManConnectionInfo.AuthenticationMechanism = this.Authentication; this.UpdateConnectionInfo(wSManConnectionInfo); wSManConnectionInfos.Add(wSManConnectionInfo); } } else { if (base.ParameterSetName == "ConnectionUri" || base.ParameterSetName == "ConnectionUriGuid") { Uri[] connectionUri = this.ConnectionUri; for (int j = 0; j < (int)connectionUri.Length; j++) { Uri uri = connectionUri[j]; WSManConnectionInfo configurationName = new WSManConnectionInfo(); configurationName.ConnectionUri = uri; configurationName.ShellUri = this.ConfigurationName; if (this.CertificateThumbprint == null) { configurationName.Credential = this.Credential; } else { configurationName.CertificateThumbprint = this.CertificateThumbprint; } configurationName.AuthenticationMechanism = this.Authentication; this.UpdateConnectionInfo(configurationName); wSManConnectionInfos.Add(configurationName); } } } return(wSManConnectionInfos); }
public override void ExecuteCmdlet() { switch (ParameterSetName) { case CreateByNameAndEnableAutoScaleParameterSet: case CreateByParentObjectAndEnableAutoScaleParameterSet: this.enableAutoScale = true; break; } if (this.IsParameterBound(c => c.WorkspaceObject)) { this.ResourceGroupName = new ResourceIdentifier(this.WorkspaceObject.Id).ResourceGroupName; this.WorkspaceName = this.WorkspaceObject.Name; } if (string.IsNullOrEmpty(this.ResourceGroupName)) { this.ResourceGroupName = this.SynapseAnalyticsClient.GetResourceGroupByWorkspaceName(this.WorkspaceName); } BigDataPoolResourceInfo existingSparkPool = null; try { existingSparkPool = this.SynapseAnalyticsClient.GetSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name); } catch { existingSparkPool = null; } if (existingSparkPool != null) { throw new AzPSInvalidOperationException(string.Format(Resources.SynapseSparkPoolExists, this.Name, this.ResourceGroupName, this.WorkspaceName)); } Workspace existingWorkspace = null; try { existingWorkspace = this.SynapseAnalyticsClient.GetWorkspace(this.ResourceGroupName, this.WorkspaceName); } catch { existingWorkspace = null; } if (existingWorkspace == null) { throw new AzPSResourceNotFoundCloudException(string.Format(Resources.WorkspaceDoesNotExist, this.WorkspaceName)); } LibraryRequirements libraryRequirements = null; if (this.IsParameterBound(c => c.LibraryRequirementsFilePath)) { var powerShellDestinationPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LibraryRequirementsFilePath); libraryRequirements = new LibraryRequirements { Filename = Path.GetFileName(powerShellDestinationPath), Content = this.ReadFileAsText(powerShellDestinationPath), }; } var createParams = new BigDataPoolResourceInfo { Location = existingWorkspace.Location, Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true), NodeCount = this.enableAutoScale ? (int?)null : this.NodeCount, NodeSizeFamily = NodeSizeFamily.MemoryOptimized, NodeSize = NodeSize, AutoScale = !this.enableAutoScale ? null : new AutoScaleProperties { Enabled = this.enableAutoScale, MinNodeCount = AutoScaleMinNodeCount, MaxNodeCount = AutoScaleMaxNodeCount }, AutoPause = !EnableAutoPause ? null : new AutoPauseProperties { Enabled = EnableAutoPause.IsPresent, DelayInMinutes = AutoPauseDelayInMinute }, SparkVersion = this.SparkVersion, LibraryRequirements = libraryRequirements }; if (this.ShouldProcess(this.Name, string.Format(Resources.CreatingSynapseSparkPool, this.ResourceGroupName, this.WorkspaceName, this.Name))) { var result = new PSSynapseSparkPool(this.SynapseAnalyticsClient.CreateOrUpdateSparkPool(this.ResourceGroupName, this.WorkspaceName, this.Name, createParams)); WriteObject(result); } }
private async Task <ResourceConfig <VirtualMachineScaleSet> > SimpleParameterSetOrchestrationModeFlexible() { //check omode params and throw error otherwise checkFlexibleOrchestrationModeParams(); int platformFaultDomainCountFlexibleDefault = 1; SwitchParameter singlePlacementGroupFlexibleDefault = false; ImageAndOsType = await _client.UpdateImageAndOsTypeAsync( ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location); // generate a domain name label if it's not specified. _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync( domainNameLabel : _cmdlet.DomainNameLabel, name : _cmdlet.VMScaleSetName, location : Location, client : _client); var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName); var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0; var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig( name: _cmdlet.PublicIpAddressName, edgeZone: _cmdlet.EdgeZone, domainNameLabel: _cmdlet.DomainNameLabel, allocationMethod: _cmdlet.AllocationMethod, //sku.Basic is not compatible with multiple placement groups sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent) ? PublicIPAddressStrategy.Sku.Basic : PublicIPAddressStrategy.Sku.Standard, zones: null); var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig( name: _cmdlet.VirtualNetworkName, edgeZone: _cmdlet.EdgeZone, addressPrefix: _cmdlet.VnetAddressPrefix); var subnet = virtualNetwork.CreateSubnet( _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix); var loadBalancer = resourceGroup.CreateLoadBalancerConfig( name: _cmdlet.LoadBalancerName, //sku.Basic is not compatible with multiple placement groups sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent) ? LoadBalancerStrategy.Sku.Basic : LoadBalancerStrategy.Sku.Standard); var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration( name: _cmdlet.FrontendPoolName, publicIpAddress: publicIpAddress); var backendAddressPool = loadBalancer.CreateBackendAddressPool( name: _cmdlet.BackendPoolName); if (_cmdlet.BackendPort != null) { var loadBalancingRuleName = _cmdlet.LoadBalancerName; foreach (var backendPort in _cmdlet.BackendPort) { loadBalancer.CreateLoadBalancingRule( name: loadBalancingRuleName + backendPort.ToString(), fronendIpConfiguration: frontendIpConfiguration, backendAddressPool: backendAddressPool, frontendPort: backendPort, backendPort: backendPort); } } _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort); var networkSecurityGroup = noZones ? null : resourceGroup.CreateNetworkSecurityGroupConfig( _cmdlet.VMScaleSetName, _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList()); var proximityPlacementGroup = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroupId); var hostGroup = resourceGroup.CreateDedicatedHostGroupSubResourceFunc(_cmdlet.HostGroupId); return(resourceGroup.CreateVirtualMachineScaleSetConfigOrchestrationModeFlexible( name: _cmdlet.VMScaleSetName, subnet: subnet, backendAdressPool: backendAddressPool, networkSecurityGroup: networkSecurityGroup, imageAndOsType: ImageAndOsType, adminUsername: _cmdlet.Credential.UserName, adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password, vmSize: _cmdlet.VmSize, instanceCount: _cmdlet.InstanceCount, dataDisks: _cmdlet.DataDiskSizeInGb, zones: _cmdlet.Zone, ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent, identity: _cmdlet.GetVmssIdentityFromArgs(), singlePlacementGroup: singlePlacementGroupFlexibleDefault, proximityPlacementGroup: proximityPlacementGroup, hostGroup: hostGroup, priority: _cmdlet.Priority, evictionPolicy: _cmdlet.EvictionPolicy, maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null, scaleInPolicy: _cmdlet.ScaleInPolicy, doNotRunExtensionsOnOverprovisionedVMs: _cmdlet.SkipExtensionsOnOverprovisionedVMs.IsPresent, encryptionAtHost: _cmdlet.EncryptionAtHost.IsPresent, platformFaultDomainCount: platformFaultDomainCountFlexibleDefault, edgeZone: _cmdlet.EdgeZone, orchestrationMode: _cmdlet.IsParameterBound(c => c.OrchestrationMode) ? _cmdlet.OrchestrationMode : null, capacityReservationId: _cmdlet.IsParameterBound(c => c.CapacityReservationGroupId) ? _cmdlet.CapacityReservationGroupId : null )); }