internal static CimInstance GetAllValues(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            CimInstance instance;
            try
            {
                CimClass cimClass = cimSession.GetClass(cimNamespace, cimClassName);
                instance = new CimInstance(cimClass);
                var cimProperties = from p in cimClass.CimClassProperties select p;
                foreach (CimPropertyDeclaration property in cimProperties)
                {
                    Console.Write("Please type value for Property '" + property.Name + "' of Type:({0}) ", property.CimType);
                    string propertyValue = Console.ReadLine();
                    if (propertyValue != null)
                    {
                        instance.CimInstanceProperties[property.Name].Value = propertyValue;
                    }
                }
            }
            catch (CimException exception)
            {
                Console.WriteLine("Unable to get schema for class " + cimClassName + " in namespace " + cimNamespace);
                PrintCimException(exception);
                return null;
            }

            return instance;
        }
		public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism? authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri)
		{
			if (activityImplementationContext != null)
			{
				base.PowerShellInstance = activityImplementationContext.PowerShellInstance;
				this.ResourceUri = resourceUri;
				this.ComputerName = computerName;
				base.PSCredential = credential;
				base.PSCertificateThumbprint = certificateThumbprint;
				base.PSAuthentication = authenticationMechanism;
				base.PSUseSsl = new bool?(useSsl);
				base.PSPort = new uint?(port);
				base.PSSessionOption = sessionOption;
				this.Session = session;
				this.SessionOptions = cimSessionOptions;
				if (moduleDefinition != null)
				{
					CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition);
					this._moduleDefinition = moduleDefinition;
				}
				return;
			}
			else
			{
				throw new ArgumentNullException("activityImplementationContext");
			}
		}
Esempio n. 3
0
		public AsyncResultEventArgsBase(CimSession session, IObservable<object> observable, AsyncResultType resultType, CimResultContext cimResultContext)
		{
			this.session = session;
			this.observable = observable;
			this.resultType = resultType;
			this.context = cimResultContext;
		}
Esempio n. 4
0
        public static void DeleteInstanceASync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            try
            {
                CimInstance deleteInstance = DeleteInstanceCore(cimSession, cimNamespace, cimClassName);
                if (deleteInstance == null)
                {
                    Console.WriteLine("DeleteInstance operation not performed");
                    return;
                }

                CimAsyncStatus enumeratedInstances = cimSession.DeleteInstanceAsync(cimNamespace, deleteInstance, GetOperationOptions());
                TestObserver<object> observer = new TestObserver<object>();
                IDisposable disposeable = enumeratedInstances.Subscribe(observer);
                observer.WaitForCompletion();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 5
0
		public CimIndicationWatcher(CimSession cimSession, string theNamespace, string queryDialect, string queryExpression, uint operationTimeout)
		{
			ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, "queryExpression");
			ValidationHelper.ValidateNoNullArgument(cimSession, "cimSession");
			theNamespace = ConstValue.GetNamespace(theNamespace);
			this.Initialize(null, cimSession, theNamespace, queryDialect, queryExpression, operationTimeout);
		}
Esempio n. 6
0
		private CimSessionProxy CreateSessionProxy(CimSession session, GetCimClassCommand cmdlet)
		{
			CimSessionProxy cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(session);
			base.SubscribeEventAndAddProxytoCache(cimSessionProxyGetCimClass);
			this.SetSessionProxyProperties(ref cimSessionProxyGetCimClass, cmdlet);
			return cimSessionProxyGetCimClass;
		}
Esempio n. 7
0
 private void GetAvailableViaCimSession(string[] moduleNames, Microsoft.Management.Infrastructure.CimSession cimSession, Uri resourceUri, string cimNamespace)
 {
     foreach (PSModuleInfo info in this.GetAvailableViaCimSessionCore(moduleNames, cimSession, resourceUri, cimNamespace))
     {
         RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(info, cimSession, resourceUri, cimNamespace);
         base.WriteObject(info);
     }
 }
Esempio n. 8
0
        internal CimJobContext(
            CimCmdletInvocationContext cmdletInvocationContext,
            CimSession session,
            object targetObject)
        {
            this.CmdletInvocationContext = cmdletInvocationContext;

            this.Session = session;
            this.TargetObject = targetObject ?? this.ClassName;
        }
Esempio n. 9
0
		internal bool DidSessionAlreadyPassedConnectivityTest(CimSession session)
		{
			bool flag = false;
			if (!this._sessionToIsConnected.TryGetValue(session, out flag))
			{
				return false;
			}
			else
			{
				return flag;
			}
		}
Esempio n. 10
0
		private void Initialize(string theComputerName, CimSession theCimSession, string theNameSpace, string theQueryDialect, string theQueryExpression, uint theOpreationTimeout)
		{
			this.enableRaisingEvents = false;
			this.status = CimIndicationWatcher.Status.Default;
			this.myLock = new object();
			this.cimRegisterCimIndication = new CimRegisterCimIndication();
			this.cimRegisterCimIndication.OnNewSubscriptionResult += new EventHandler<CimSubscriptionEventArgs>(this.NewSubscriptionResultHandler);
			this.cimSession = theCimSession;
			this.nameSpace = theNameSpace;
			this.queryDialect = ConstValue.GetQueryDialectWithDefault(theQueryDialect);
			this.queryExpression = theQueryExpression;
			this.opreationTimeout = theOpreationTimeout;
			this.computerName = theComputerName;
		}
Esempio n. 11
0
		internal Exception GetExceptionIfBrokenSession(CimSession potentiallyBrokenSession, bool skipTestConnection, out bool sessionWasAlreadyTerminated)
		{
			CimInstance cimInstance = null;
			CimException cimException = null;
			if (!this.IsSessionTerminated(potentiallyBrokenSession))
			{
				Exception exception = null;
				if (!skipTestConnection && !this.DidSessionAlreadyPassedConnectivityTest(potentiallyBrokenSession))
				{
					try
					{
						potentiallyBrokenSession.TestConnection(out cimInstance, out cimException);
						exception = cimException;
						if (exception == null)
						{
							this.MarkSessionAsConnected(potentiallyBrokenSession);
						}
					}
					catch (InvalidOperationException invalidOperationException1)
					{
						InvalidOperationException invalidOperationException = invalidOperationException1;
						exception = invalidOperationException;
					}
				}
				if (exception == null)
				{
					sessionWasAlreadyTerminated = false;
					return exception;
				}
				else
				{
					this.MarkSessionAsTerminated(potentiallyBrokenSession, out sessionWasAlreadyTerminated);
					return exception;
				}
			}
			else
			{
				sessionWasAlreadyTerminated = true;
				return null;
			}
		}
Esempio n. 12
0
		internal PSObject AddObjectToCache(CimSession session, uint sessionId, Guid instanceId, string name, string computerName, ProtocolType protocol)
		{
			HashSet<CimSessionWrapper> cimSessionWrappers = null;
			CimSessionWrapper cimSessionWrapper = new CimSessionWrapper(sessionId, instanceId, name, computerName, session, protocol);
			if (!this.curCimSessionsByComputerName.TryGetValue(computerName, out cimSessionWrappers))
			{
				cimSessionWrappers = new HashSet<CimSessionWrapper>();
				this.curCimSessionsByComputerName.Add(computerName, cimSessionWrappers);
			}
			cimSessionWrappers.Add(cimSessionWrapper);
			if (!this.curCimSessionsByName.TryGetValue(name, out cimSessionWrappers))
			{
				cimSessionWrappers = new HashSet<CimSessionWrapper>();
				this.curCimSessionsByName.Add(name, cimSessionWrappers);
			}
			cimSessionWrappers.Add(cimSessionWrapper);
			this.curCimSessionsByInstanceId.Add(instanceId, cimSessionWrapper);
			this.curCimSessionsById.Add(sessionId, cimSessionWrapper);
			this.curCimSessionWrapper.Add(session, cimSessionWrapper);
			return cimSessionWrapper.GetPSObject();
		}
Esempio n. 13
0
		internal void AddSessionToCache(CimSession cimSession, XOperationContextBase context, CmdletOperationBase cmdlet)
		{
			string str;
			DebugHelper.WriteLogEx();
			CimNewSession.CimTestCimSessionContext cimTestCimSessionContext = context as CimNewSession.CimTestCimSessionContext;
			uint num = this.sessionState.GenerateSessionId();
			string name = cimTestCimSessionContext.CimSessionWrapper.Name;
			if (name != null)
			{
				str = name;
			}
			else
			{
				object[] cimSessionClassName = new object[2];
				cimSessionClassName[0] = CimSessionState.CimSessionClassName;
				cimSessionClassName[1] = num;
				str = string.Format(CultureInfo.CurrentUICulture, "{0}{1}", cimSessionClassName);
			}
			string str1 = str;
			CimSession cimSession1 = cimTestCimSessionContext.Proxy.Detach();
			PSObject cache = this.sessionState.AddObjectToCache(cimSession1, num, cimSession1.InstanceId, str1, cimTestCimSessionContext.CimSessionWrapper.ComputerName, cimTestCimSessionContext.Proxy.Protocol);
			cmdlet.WriteObject(cache, null);
		}
        internal static Dictionary<string, object> GetKeyValues(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            Dictionary<string, object> propertyValues = new Dictionary<string, object>();
            try
            {
                CimClass cimClass = cimSession.GetClass(cimNamespace, cimClassName);
                var keyProperties = from p in cimClass.CimClassProperties where ((p.Flags & CimFlags.Key) == CimFlags.Key) select p;
                foreach (CimPropertyDeclaration keyProperty in keyProperties)
                {
                    Console.Write("Please type Key value for Property '" + keyProperty.Name + "' of Type:({0}) ", keyProperty.CimType);
                    string propertyValue = Console.ReadLine();
                    propertyValues.Add(keyProperty.Name, propertyValue);
                }
            }
            catch (CimException exception)
            {
                Console.WriteLine("Unable to get schema for class " + cimClassName + " in namespace " + cimNamespace);
                PrintCimException(exception);
                return null;
            }

            return propertyValues;
        }
		public AsyncResultCompleteEventArgs(CimSession session, IObservable<object> observable) : base(session, observable, (AsyncResultType)2)
		{
		}
Esempio n. 16
0
 private CimInstance ConvertToDefault(ScheduledJobTrigger trigger, CimSession cimSession)
 {
     CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskTrigger");
     CimInstance result = new CimInstance(cimClass);
     AddCommonProperties(trigger, result);
     return result;
 }
Esempio n. 17
0
		public static CimSession Create(string computerName)
		{
			return CimSession.Create(computerName, null);
		}
Esempio n. 18
0
		public static CimAsyncResult<CimSession> CreateAsync(string computerName)
		{
			return CimSession.CreateAsync(computerName, null);
		}
Esempio n. 19
0
        private PSModuleInfo ImportModule_RemotelyViaCimModuleData(
            ImportModuleOptions importModuleOptions,
            RemoteDiscoveryHelper.CimModule remoteCimModule,
            CimSession cimSession)
        {
            try
            {
                if (remoteCimModule.MainManifest == null)
                {
                    string errorMessage = string.Format(
                        CultureInfo.InvariantCulture,
                        Modules.EmptyModuleManifest,
                        remoteCimModule.ModuleName + ".psd1");
                    ArgumentException argumentException = new ArgumentException(errorMessage);
                    throw argumentException;
                }

                bool containedErrors = false;
                PSModuleInfo moduleInfo = null;

                //
                // read the original manifest
                //
                string temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
                    remoteCimModule.ModuleName,
                    null,
                    cimSession.ComputerName,
                    this.Context.CurrentRunspace);
                string temporaryModuleManifestPath = Path.Combine(
                    temporaryModuleDirectory,
                    remoteCimModule.ModuleName + ".psd1");

                Hashtable data = null;
                Hashtable localizedData = null;
                {
                    ScriptBlockAst scriptBlockAst = null;
                    Token[] throwAwayTokens;
                    ParseError[] parseErrors;
                    scriptBlockAst = Parser.ParseInput(
                        remoteCimModule.MainManifest.FileData,
                        temporaryModuleManifestPath,
                        out throwAwayTokens,
                        out parseErrors);
                    if ((scriptBlockAst == null) ||
                        (parseErrors != null && parseErrors.Length > 0))
                    {
                        throw new ParseException(parseErrors);
                    }

                    ScriptBlock scriptBlock = new ScriptBlock(scriptBlockAst, isFilter: false);
                    data = LoadModuleManifestData(
                        temporaryModuleManifestPath,
                        scriptBlock,
                        ModuleManifestMembers,
                        ManifestProcessingFlags.NullOnFirstError | ManifestProcessingFlags.WriteErrors, /* - don't load elements */
                        ref containedErrors);

                    if ((data == null) || containedErrors)
                    {
                        return null;
                    }
                    localizedData = data;
                }

                // 
                // flatten module contents and rewrite the manifest to point to the flattened file hierarchy
                //

                // recalculate module path, taking into account the module version fetched above
                Version moduleVersion;
                if (!GetScalarFromData<Version>(data, null, "ModuleVersion", 0, out moduleVersion))
                {
                    moduleVersion = null;
                }
                temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
                    remoteCimModule.ModuleName,
                    moduleVersion,
                    cimSession.ComputerName,
                    this.Context.CurrentRunspace);
                temporaryModuleManifestPath = Path.Combine(
                    temporaryModuleDirectory,
                    remoteCimModule.ModuleName + ".psd1");
                // avoid loading an already loaded module
                PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
                    temporaryModuleManifestPath, this.BasePrefix, importModuleOptions);
                if (alreadyImportedModule != null)
                {
                    return alreadyImportedModule;
                }
                try
                {
                    Directory.CreateDirectory(temporaryModuleDirectory);

                    IEnumerable<string> typesToProcess = CreateCimModuleFiles(
                        remoteCimModule,
                        RemoteDiscoveryHelper.CimFileCode.TypesV1,
                        cimModuleFile => IsTypesPs1XmlFile(cimModuleFile, data),
                        temporaryModuleDirectory);
                    IEnumerable<string> formatsToProcess = CreateCimModuleFiles(
                        remoteCimModule,
                        RemoteDiscoveryHelper.CimFileCode.FormatV1,
                        cimModuleFile => IsFormatPs1XmlFile(cimModuleFile, data),
                        temporaryModuleDirectory);
                    IEnumerable<string> nestedModules = CreateCimModuleFiles(
                        remoteCimModule,
                        RemoteDiscoveryHelper.CimFileCode.CmdletizationV1,
                        IsCmdletizationFile,
                        temporaryModuleDirectory);
                    data = RemoteDiscoveryHelper.RewriteManifest(
                        data,
                        nestedModules: nestedModules,
                        typesToProcess: typesToProcess,
                        formatsToProcess: formatsToProcess);
                    localizedData = RemoteDiscoveryHelper.RewriteManifest(localizedData);

                    //
                    // import the module 
                    // (from memory - this avoids the authenticode signature problems 
                    // that would be introduced by rewriting the contents of the manifest)
                    //
                    moduleInfo = LoadModuleManifest(
                        temporaryModuleManifestPath,
                        null, //scriptInfo
                        data,
                        localizedData,
                        ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
                        BaseMinimumVersion,
                        BaseMaximumVersion,
                        BaseRequiredVersion,
                        BaseGuid,
                        ref importModuleOptions,
                        ref containedErrors);
                    if (moduleInfo == null)
                    {
                        return null;
                    }
                    foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
                    {
                        Type cmdletAdapter;
                        bool gotCmdletAdapter = PSPrimitiveDictionary.TryPathGet(
                            nestedModule.PrivateData as IDictionary,
                            out cmdletAdapter,
                            "CmdletsOverObjects",
                            "CmdletAdapter");
                        Dbg.Assert(gotCmdletAdapter, "PrivateData from cdxml should always include cmdlet adapter");
                        if (!cmdletAdapter.AssemblyQualifiedName.Equals(StringLiterals.DefaultCmdletAdapter, StringComparison.OrdinalIgnoreCase))
                        {
                            string errorMessage = string.Format(
                                CultureInfo.InvariantCulture,
                                CmdletizationCoreResources.ImportModule_UnsupportedCmdletAdapter,
                                cmdletAdapter.FullName);
                            ErrorRecord errorRecord = new ErrorRecord(
                                new InvalidOperationException(errorMessage),
                                "UnsupportedCmdletAdapter",
                                ErrorCategory.InvalidData,
                                cmdletAdapter);
                            this.ThrowTerminatingError(errorRecord);
                        }
                    }
                    if (IsMixedModePsCimModule(remoteCimModule))
                    {
                        // warn that some commands have not been imported
                        string warningMessage = string.Format(
                            CultureInfo.InvariantCulture,
                            Modules.MixedModuleOverCimSessionWarning,
                            remoteCimModule.ModuleName);
                        this.WriteWarning(warningMessage);
                    }

                    //
                    // store the default session 
                    //
                    Dbg.Assert(moduleInfo.ModuleType == ModuleType.Manifest, "Remote discovery should always produce a 'manifest' module");
                    Dbg.Assert(moduleInfo.NestedModules != null, "Remote discovery should always produce a 'manifest' module with nested modules entry");
                    Dbg.Assert(moduleInfo.NestedModules.Count > 0, "Remote discovery should always produce a 'manifest' module with some nested modules");
                    foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
                    {
                        IDictionary cmdletsOverObjectsPrivateData;
                        bool cmdletsOverObjectsPrivateDataWasFound = PSPrimitiveDictionary.TryPathGet<IDictionary>(
                            nestedModule.PrivateData as IDictionary,
                            out cmdletsOverObjectsPrivateData,
                            ScriptWriter.PrivateDataKey_CmdletsOverObjects);
                        Dbg.Assert(cmdletsOverObjectsPrivateDataWasFound, "Cmdletization should always set the PrivateData properly");
                        cmdletsOverObjectsPrivateData[ScriptWriter.PrivateDataKey_DefaultSession] = cimSession;
                    }

                    //
                    // make sure the temporary folder gets removed when the module is removed
                    //
                    const string onRemoveScriptBody =
                        @"
                        Microsoft.PowerShell.Management\Remove-Item `
                            -LiteralPath $temporaryModulePath `
                            -Force `
                            -Recurse `
                            -ErrorAction SilentlyContinue

                        if ($previousOnRemoveScript -ne $null)
                        {
                            & $previousOnRemoveScript $args
                        }
                        ";
                    ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
                    onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure();
                    // create a separate scope for variables set below
                    onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModuleDirectory);
                    onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
                    moduleInfo.OnRemove = onRemoveScriptBlock;

                    //
                    // Some processing common for local and remote modules
                    //
                    AddModuleToModuleTables(
                        this.Context,
                        this.TargetSessionState.Internal,
                        moduleInfo);
                    if (BasePassThru)
                    {
                        WriteObject(moduleInfo);
                    }

                    return moduleInfo;
                }
                catch
                {
                    if (Directory.Exists(temporaryModuleDirectory))
                    {
                        Directory.Delete(temporaryModuleDirectory, recursive: true);
                    }
                    throw;
                }
                finally
                {
                    if (moduleInfo == null)
                    {
                        if (Directory.Exists(temporaryModuleDirectory))
                        {
                            Directory.Delete(temporaryModuleDirectory, recursive: true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, remoteCimModule.ModuleName);
                this.WriteError(errorRecord);
                return null;
            }
        }
Esempio n. 20
0
		public AsyncResultObjectEventArgs(CimSession session, IObservable<object> observable, object resultObject) : base(session, observable, 0)
		{
			this.resultObject = resultObject;
		}
Esempio n. 21
0
		private CimSessionProxy CreateSessionProxy(CimSession session, NewCimInstanceCommand cmdlet)
		{
			CimSessionProxy cimSessionProxyNewCimInstance = new CimSessionProxyNewCimInstance(session, this);
			base.SubscribeEventAndAddProxytoCache(cimSessionProxyNewCimInstance);
			this.SetSessionProxyProperties(ref cimSessionProxyNewCimInstance, cmdlet);
			return cimSessionProxyNewCimInstance;
		}
Esempio n. 22
0
        private IEnumerable<PSModuleInfo> GetAvailableViaCimSessionCore(IEnumerable<string> moduleNames,
                                                                        CimSession cimSession, Uri resourceUri,
                                                                        string cimNamespace)
        {
            IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules(
                cimSession,
                resourceUri,
                cimNamespace,
                moduleNames,
                true /* onlyManifests */,
                this,
                this.CancellationToken);

            IEnumerable<PSModuleInfo> remoteModuleInfos = remoteModules
                .Select(cimModule => this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName))
                .Where(moduleInfo => moduleInfo != null);

            return remoteModuleInfos;
        }
Esempio n. 23
0
        private void GetAvailableViaCimSession(IEnumerable<string> names, IDictionary<string, ModuleSpecification> moduleSpecTable,
                                               CimSession cimSession, Uri resourceUri, string cimNamespace)
        {
            var remoteModules = GetAvailableViaCimSessionCore(names, cimSession, resourceUri, cimNamespace);

            foreach (var remoteModule in remoteModules.Where(remoteModule => ModuleMatch(remoteModule, moduleSpecTable, PSEdition))
                )
            {
                RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, cimSession, resourceUri,
                                                                       cimNamespace);
                this.WriteObject(remoteModule);
            }
        }
Esempio n. 24
0
		protected CimSessionProxy CreateCimSessionProxy(CimSession session, bool passThru)
		{
			CimSessionProxy cimSessionProxySetCimInstance = new CimSessionProxySetCimInstance(session, passThru);
			this.SubscribeEventAndAddProxytoCache(cimSessionProxySetCimInstance);
			return cimSessionProxySetCimInstance;
		}
Esempio n. 25
0
 private IEnumerable <PSModuleInfo> GetAvailableViaCimSessionCore(IEnumerable <string> moduleNames, Microsoft.Management.Infrastructure.CimSession cimSession, Uri resourceUri, string cimNamespace)
 {
     return(from cimModule in RemoteDiscoveryHelper.GetCimModules(cimSession, resourceUri, cimNamespace, moduleNames, true, this, this.CancellationToken)
            select this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName) into moduleInfo
            where moduleInfo != null
            select moduleInfo);
 }
Esempio n. 26
0
        private CimInstance ConvertToWeekly(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskWeeklyTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["DaysOfWeek"].Value = ScheduledJobWTS.ConvertDaysOfWeekToMask(trigger.DaysOfWeek);
            cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            cimInstance.CimInstanceProperties["WeeksInterval"].Value = trigger.Interval;

            AddCommonProperties(trigger, cimInstance);
            return cimInstance;
        }
Esempio n. 27
0
        private void ImportModule_RemotelyViaCimSession(
            ImportModuleOptions importModuleOptions,
            string[] moduleNames,
            CimSession cimSession,
            Uri resourceUri,
            string cimNamespace)
        {
            //
            // find all remote PS-CIM modules
            //
            IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules(
                cimSession,
                resourceUri,
                cimNamespace,
                moduleNames,
                false /* onlyManifests */,
                this,
                this.CancellationToken).ToList();

            IEnumerable<RemoteDiscoveryHelper.CimModule> remotePsCimModules = remoteModules.Where(cimModule => cimModule.IsPsCimModule);
            IEnumerable<string> remotePsrpModuleNames = remoteModules.Where(cimModule => !cimModule.IsPsCimModule).Select(cimModule => cimModule.ModuleName);
            foreach (string psrpModuleName in remotePsrpModuleNames)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture,
                    Modules.PsModuleOverCimSessionError,
                    psrpModuleName);
                ErrorRecord errorRecord = new ErrorRecord(
                    new ArgumentException(errorMessage),
                    "PsModuleOverCimSessionError",
                    ErrorCategory.InvalidArgument,
                    psrpModuleName);
                this.WriteError(errorRecord);
            }

            //
            // report an error if some modules were not found
            //
            IEnumerable<string> allFoundModuleNames = remoteModules.Select(cimModule => cimModule.ModuleName).ToList();
            foreach (string requestedModuleName in moduleNames)
            {
                var wildcardPattern = WildcardPattern.Get(requestedModuleName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
                bool requestedModuleWasFound = allFoundModuleNames.Any(foundModuleName => wildcardPattern.IsMatch(foundModuleName));
                if (!requestedModuleWasFound)
                {
                    string message = StringUtil.Format(Modules.ModuleNotFound, requestedModuleName);
                    FileNotFoundException fnf = new FileNotFoundException(message);
                    ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
                        ErrorCategory.ResourceUnavailable, requestedModuleName);
                    WriteError(er);
                }
            }

            //
            // import the PS-CIM modules
            //
            foreach (RemoteDiscoveryHelper.CimModule remoteCimModule in remotePsCimModules)
            {
                ImportModule_RemotelyViaCimModuleData(importModuleOptions, remoteCimModule, cimSession);
            }
        }
Esempio n. 28
0
        private CimInstance ConvertToOnce(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskTimeTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);

            if (trigger.RepetitionInterval != null && trigger.RepetitionDuration != null)
            {
                CimClass cimRepClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskRepetitionPattern");
                CimInstance cimRepInstance = new CimInstance(cimRepClass);

                cimRepInstance.CimInstanceProperties["Interval"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionInterval.Value);

                if (trigger.RepetitionDuration == TimeSpan.MaxValue)
                {
                    cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = false;
                }
                else
                {
                    cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = true;
                    cimRepInstance.CimInstanceProperties["Duration"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionDuration.Value);
                }

                cimInstance.CimInstanceProperties["Repetition"].Value = cimRepInstance;
            }

            AddCommonProperties(trigger, cimInstance);
            return cimInstance;
        }
Esempio n. 29
0
		protected CimSessionProxy CreateCimSessionProxy(CimSession session)
		{
			CimSessionProxy cimSessionProxy = new CimSessionProxy(session);
			this.SubscribeEventAndAddProxytoCache(cimSessionProxy);
			return cimSessionProxy;
		}
Esempio n. 30
0
        private CimInstance ConvertToAtLogon(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskLogonTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);

            // Convert the "AllUsers" name ("*" character) to null for Task Scheduler.
            string userId = (ScheduledJobTrigger.IsAllUsers(trigger.User)) ? null : trigger.User;
            cimInstance.CimInstanceProperties["UserId"].Value = userId;

            AddCommonProperties(trigger, cimInstance);
            return cimInstance;
        }
Esempio n. 31
0
		public AsyncResultEventArgsBase(CimSession session, IObservable<object> observable, AsyncResultType resultType)
		{
			this.session = session;
			this.observable = observable;
			this.resultType = resultType;
		}
Esempio n. 32
0
        private CimInstance ConvertToAtStartup(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskBootTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);

            AddCommonProperties(trigger, cimInstance);
            return cimInstance;
        }
Esempio n. 33
0
		public AsyncResultErrorEventArgs(CimSession session, IObservable<object> observable, Exception error) : base(session, observable, (AsyncResultType)1)
		{
			this.error = error;
		}
Esempio n. 34
-1
        public static void CreateInstanceSync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            try
            {
                CimInstance createInstance = CreateInstanceCore(cimSession, cimNamespace, cimClassName);
                if (createInstance == null)
                {
                    Console.WriteLine("CreateInstance operation not performed");
                    return;
                }

                CimInstance cimInstance = cimSession.CreateInstance(cimNamespace, createInstance);
                Console.WriteLine("Instance Created Successfully");
                PrintCimInstance(cimInstance);
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }