Exemple #1
0
        public void ConvertFromDictionaryParametersSucceeds()
        {
            // Arrange
            var extraConversionKeyName = "biz.dfch.CS.Commons.ConversionKey.ThatIsNotDefinedInTheTargetDataTransferObjectAndWillBeIgnoredOnConversion";

            var parameters = new DictionaryParameters
            {
                { STRING_PROPERTY_WITH_ANNOTATION_ANNOTATION, "arbitrary-string-value" }
                ,
                { LONG_PROPERTY_WITH_ANNOTATION_ANNOTATION, 42L }
                ,
                { extraConversionKeyName, "some-other-arbitrary-string-value" }
            };

            // Act
            var result = ConversionKeyConverter.Convert <ClassWithConversionKeyAttributes>(parameters);

            // Assert
            Assert.IsNotNull(result);
            if (!result.IsValid())
            {
                var validationResults = result.GetValidationResults();
                foreach (var validationResult in validationResults)
                {
                    System.Diagnostics.Debug.WriteLine(validationResult.ErrorMessage);
                }
            }
            Assert.IsTrue(result.IsValid());

            Assert.AreEqual("arbitrary-string-value", result.StringPropertyWithAnnotation);
            Assert.AreEqual(42L, result.LongPropertyWithAnnotation);
            Assert.IsNull(result.StringPropertyWithoutAnnotation);
            Assert.AreEqual(0, result.LongPropertyWithoutAnnotation);
        }
        public static IList <TBase> Convert <TBase>(DictionaryParameters dictionaryParameters, string version)
            where TBase : ConversionKeyBaseDto
        {
            var result = _converter.Convert <TBase, ConversionKeyAttribute>(dictionaryParameters, version);

            return(result);
        }
Exemple #3
0
        public static T Convert <T>(DictionaryParameters dictionaryParameters, bool includeAllProperties)
            where T : EnvironmentVariableBaseDto, new()
        {
            var result = _converter.Convert <T, EnvironmentVariableAttribute>(dictionaryParameters, includeAllProperties);

            return(result);
        }
        public void Initialise(BaseDto configuration, DictionaryParameters parameters)
        {
            Contract.Assert(configuration is ScheduledJobsWorkerConfiguration);
            
            parameters = parameters ?? new DictionaryParameters();

            var cfg = configuration as ScheduledJobsWorkerConfiguration;

            // get communication update and retry variables
            cfg.UpdateIntervalInMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateIntervalMinutes"]);
            cfg.UpdateIntervalInMinutes = 
                (0 != cfg.UpdateIntervalInMinutes) ? 
                cfg.UpdateIntervalInMinutes : 
                ScheduledJobsWorkerConfiguration.UPDATE_INTERVAL_IN_MINUTES_DEFAULT;

            cfg.ServerNotReachableRetries = Convert.ToInt32(ConfigurationManager.AppSettings["ServerNotReachableRetries"]);
            cfg.ServerNotReachableRetries = 
                cfg.UpdateIntervalInMinutes * (0 != cfg.ServerNotReachableRetries ?
                cfg.ServerNotReachableRetries : 
                ScheduledJobsWorkerConfiguration.SERVER_NOT_REACHABLE_RETRIES_DEFAULT);

            // apply parameters if overridden on command line
            var uri = ConfigurationManager.AppSettings["Uri"];
            if(parameters.ContainsKey("args0"))
            {
                uri = parameters["args0"] as string;
            }
            Contract.Assert(!string.IsNullOrWhiteSpace(uri));
            cfg.Uri = new Uri(uri);

            cfg.ManagementUriName = ConfigurationManager.AppSettings["ManagementUri"];
            if(parameters.ContainsKey("args1"))
            {
                cfg.ManagementUriName = parameters["args1"] as string;
            }
            Contract.Assert(!string.IsNullOrWhiteSpace(cfg.ManagementUriName));

            // load plugins
            var configurationLoader = new PluginLoaderConfigurationFromAppSettingsLoader();
            var pluginLoader = new PluginLoader(configurationLoader, cfg.Logger);
            cfg.Plugins = pluginLoader.InitialiseAndLoad();
            Contract.Assert(0 < cfg.Plugins.Count, "No plugins loaded. Cannot continue.");

            // get credentials to connect to Appclusive HOST server
            var credentialSection = ConfigurationManager.GetSection(AppclusiveCredentialSection.SECTION_NAME) as AppclusiveCredentialSection;
            if(null == credentialSection)
            {
                Trace.WriteLine("No credential in app.config section '{0}' defined. Using 'DefaultNetworkCredentials'.", AppclusiveCredentialSection.SECTION_NAME, "");
                
                cfg.Credential = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                Trace.WriteLine("Credential in app.config section '{0}' found. Using '{1}\\{2}'.", AppclusiveCredentialSection.SECTION_NAME, credentialSection.Domain, credentialSection.Username);

                var networkCredential = new NetworkCredential(credentialSection.Username, credentialSection.Password, credentialSection.Domain);
                Contract.Assert(null != networkCredential);
                cfg.Credential = networkCredential;
            }
        }
Exemple #5
0
        public static T Convert <T>(DictionaryParameters dictionaryParameters)
            where T : EnvironmentVariableBaseDto, new()
        {
            var result = _converter.Convert <T, EnvironmentVariableAttribute>(dictionaryParameters, false);

            return(result);
        }
Exemple #6
0
        public static IList <TBase> Convert <TBase>(DictionaryParameters dictionaryParameters, string version, bool includeAllProperies)
            where TBase : EnvironmentVariableBaseDto
        {
            var result = _converter.Convert <TBase, EnvironmentVariableAttribute>(dictionaryParameters, version, includeAllProperies);

            return(result);
        }
Exemple #7
0
        public void ConvertingViaBaseDtoSucceeds()
        {
            // Arrange
            const string name        = "arbitrary-name";
            const string description = "optional-description";
            const string size        = "40";

            var StringPropertyWithAnnotationAnnotationValue      = "arbitrary-string";
            var LongPropertyWithAnnotationAnnotationValue        = 42L;
            var StringPropertyWithAnnotationAnnotationType1Value = "arbitrary-string-1";
            var LongPropertyWithAnnotationAnnotationType1Value   = 1L;
            var StringPropertyWithAnnotationAnnotationType2Value = "arbitrary-string-2";
            var LongPropertyWithAnnotationAnnotationType2Value   = 2L;

            var dictionaryParameters = new DictionaryParameters()
            {
                { STRING_PROPERTY_WITH_ANNOTATION_ANNOTATION, StringPropertyWithAnnotationAnnotationValue }
                ,
                { LONG_PROPERTY_WITH_ANNOTATION_ANNOTATION, LongPropertyWithAnnotationAnnotationValue }
                ,
                { STRING_PROPERTY_WITH_ANNOTATION_ANNOTATION_TYPE1, StringPropertyWithAnnotationAnnotationType1Value }
                ,
                { LONG_PROPERTY_WITH_ANNOTATION_ANNOTATION_TYPE1, LongPropertyWithAnnotationAnnotationType1Value }
                ,
                { STRING_PROPERTY_WITH_ANNOTATION_ANNOTATION_TYPE2, StringPropertyWithAnnotationAnnotationType2Value }
                ,
                { LONG_PROPERTY_WITH_ANNOTATION_ANNOTATION_TYPE2, LongPropertyWithAnnotationAnnotationType2Value }
                ,
                { "arbitrary-other-key", "arbitrary-value" }
            };

            // Act
            var result = ConversionKeyConverter.Convert <ClassWithConversionKeyAttributesAsTBase>(dictionaryParameters, null);

            // Assert

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);

            foreach (var dto in result)
            {
                Assert.IsTrue(dto.IsValid(), dto.GetType().FullName);
            }

            Assert.IsTrue(result[0] is ClassWithConversionKeyAttributesAsDerivedType1 || result[1] is ClassWithConversionKeyAttributesAsDerivedType1);
            Assert.IsTrue(result[0] is ClassWithConversionKeyAttributesAsDerivedType2 || result[1] is ClassWithConversionKeyAttributesAsDerivedType2);

            var type1 = result[0] is ClassWithConversionKeyAttributesAsDerivedType1 ? result[0] : result[1];

            Assert.IsNotNull(type1);
            var type2 = result[0] is ClassWithConversionKeyAttributesAsDerivedType2 ? result[0] : result[1];

            Assert.IsNotNull(type2);

            Assert.AreEqual(StringPropertyWithAnnotationAnnotationType1Value, type1.StringPropertyWithAnnotation);
            Assert.AreEqual(LongPropertyWithAnnotationAnnotationType1Value, type1.LongPropertyWithAnnotation);

            Assert.AreEqual(StringPropertyWithAnnotationAnnotationType2Value, type2.StringPropertyWithAnnotation);
            Assert.AreEqual(LongPropertyWithAnnotationAnnotationType2Value, type2.LongPropertyWithAnnotation);
        }
Exemple #8
0
        public static T Convert <T>(DictionaryParameters dictionaryParameters, bool includeAllProperties)
            where T : DictionaryParametersBaseDto, new()
        {
            var result = _converter.Convert <T, DictionaryParametersKeyAttribute>(dictionaryParameters, includeAllProperties);

            return(result);
        }
        public override bool Invoke(DictionaryParameters parameters, IInvocationResult jobResult)
        {
            var result = base.Invoke(parameters, jobResult);
            if(!result)
            {
                return result;
            }

            var message = new StringBuilder();
            message.AppendLine("[{0}] DefaultPlugin.Invoke ...");
            message.AppendLine();

            foreach(KeyValuePair<string, object> item in parameters)
            {
                message.AppendFormat("{0}: '{1}'", item.Key, item.Value ?? item.Value.ToString());
                message.AppendLine();
            }
            message.AppendLine("DefaultPlugin.Invoke() COMPLETED.");
            message.AppendLine();
            
            Logger.WriteLine("[{0}] {1}", System.Diagnostics.Trace.CorrelationManager.ActivityId, message.ToString());

            result = true;
            
            jobResult.Succeeded = result;
            jobResult.Code = 1;
            jobResult.Message = "DefaultPlugin.Invoke COMPLETED and logged the intended operation to a tracing facility.";
            jobResult.Description = message.ToString();
            jobResult.InnerJobResult = null;

            return result;
        }
        public void CanAddReturnsFalse()
        {
            // Arrange
            var sut = new DictionaryParameters()
            {
                { "Key1.1", "arbitrary-value1-1" }
                ,
                { "Key1.2", 11L }
                ,
                { "DuplicateKey", "arbitrary-value" }
            };

            var objectToMerge = new DictionaryParameters()
            {
                { "Key2.1", "arbitrary-value-2.1" }
                ,
                { "Key2.2", 22L }
                ,
                { "DuplicateKey", "arbitrary-value" }
            };

            // Act
            var result = sut.CanAdd(objectToMerge);

            // Assert
            Assert.IsFalse(result);
        }
        public void AddThrowsArgumentException()
        {
            // Arrange
            var sut = new DictionaryParameters()
            {
                { "Key1.1", "arbitrary-value1-1" }
                ,
                { "Key1.2", 11L }
                ,
                { "DuplicateKey", "arbitrary-value" }
            };

            var objectToMerge = new DictionaryParameters()
            {
                { "Key2.1", "arbitrary-value-2.1" }
                ,
                { "Key2.2", 22L }
                ,
                { "DuplicateKey", "arbitrary-value" }
            };

            // Act
            var result = sut.Add(objectToMerge);

            // Assert
            // N/A
        }
        public override bool Invoke(DictionaryParameters parameters, IInvocationResult jobResult)
        {
            var result = IsActive;

            var description = string.Format("ActivityId '{0}'.", System.Diagnostics.Trace.CorrelationManager.ActivityId.ToString());
            jobResult.Description = description;
            jobResult.Succeeded = result;
            
            if(!result)
            {
                var message = "Plugin not active";

                Logger.Warn("{0} {1}. Nothing to do.", description, message);

                jobResult.Code = Constants.InvocationResultCodes.ERROR_SERVICE_NOT_ACTIVE;
                jobResult.Message = message;
            }
            else
            {
                var message = "Plugin active";

                jobResult.Code = Constants.InvocationResultCodes.ERROR_INVALID_FUNCTION;
                jobResult.Message = message;
            }
            
            return result;
        }
        public void NewDictionaryParametersFromJsonStringSucceeds()
        {
            // Arrange
            var jsonString = "{\"NullKey7\":null,\"ArrayKey6\":[\"val1\",\"val2\",\"val3\"],\"IntKey4\":5,\"StringKey1\":\"arbitrary-value1\",\"LongKey3\":42,\"ArbitraryObjectKey5\":{\"UserName\":\"arbitrary-user\",\"Password\":\"arbitrary-password\",\"SecurePassword\":{\"Length\":18},\"Domain\":\"\"},\"EmptyStringKey2\":\"\"}";

            // Act
            var sut = new DictionaryParameters(jsonString);

            // Assert
            Assert.IsTrue(sut.ContainsKey("StringKey1"));
            Assert.AreEqual("arbitrary-value1", sut["StringKey1"]);
            Assert.IsTrue(sut.ContainsKey("EmptyStringKey2"));
            Assert.AreEqual("", sut["EmptyStringKey2"]);
            Assert.IsTrue(sut.ContainsKey("LongKey3"));
            Assert.AreEqual(42L, sut["LongKey3"]);
            Assert.IsTrue(sut.ContainsKey("IntKey4"));
            Assert.AreEqual(5L, sut["IntKey4"]);
            Assert.IsTrue(sut.ContainsKey("ArbitraryObjectKey5"));
            Assert.IsTrue(sut.ContainsKey("ArrayKey6"));
            Assert.IsTrue(sut["ArrayKey6"] is List <object>);
            var list = sut["ArrayKey6"] as List <object>;

            Assert.AreEqual(3, list.Count);
            Assert.IsTrue(list.Contains("val1"));
            Assert.IsTrue(list.Contains("val2"));
            Assert.IsTrue(list.Contains("val3"));
            Assert.IsTrue(sut.ContainsKey("NullKey7"));
            Assert.IsNull(sut["NullKey7"]);
        }
Exemple #14
0
        // returns a list of all deserialised DTOs based on TBase
        // if nameSpace is null then the namespace of TBase is used for resolving derived types
        public IList <TBase> Convert <TBase, TAttribute>(DictionaryParameters dictionaryParameters, string nameSpace, bool includeAllProperties)
            where TBase : ConvertibleBaseDto
            where TAttribute : ConversionKeyBaseAttribute
        {
            // create list to be returned
            var tBaseList = new List <TBase>();

            if (string.IsNullOrWhiteSpace(nameSpace))
            {
                nameSpace = typeof(TBase).Namespace;
                Contract.Assert(!string.IsNullOrWhiteSpace(nameSpace));
            }

            var types = GetDerivedTypes <TBase>(typeof(TBase).Assembly, nameSpace);

            foreach (var type in types)
            {
                var genericMethodInfo = _methodInfoConvertFromDictionary.MakeGenericMethod(type, typeof(TAttribute));
                Contract.Assert(null != genericMethodInfo, typeof(TAttribute).FullName);

                var dtoDerivedFromTBase = (TBase)genericMethodInfo.Invoke(this, new object[] { dictionaryParameters, includeAllProperties });
                tBaseList.Add(dtoDerivedFromTBase);
            }

            return(tBaseList);
        }
        public void DictionaryParametersToStringReturnsNestedObjectsAndIndentedJson()
        {
            // Arrange
            var nested = new DictionaryParameters()
            {
                { "Key2.1", "arbitrary-value-2.1" }
                ,
                { "Key2.2", 22L }
                ,
                { "ArbitraryKey", "arbitrary-nested-value" }
            };

            var sut = new DictionaryParameters()
            {
                { "Key1.1", "arbitrary-value1-1" }
                ,
                { "Key1.2", 11L }
                ,
                { "Nested", nested }
                ,
                { "Key1.3", "arbitrary-value" }
            };

            // Act
            var result = sut.ToString();

            // Assert
            Assert.IsFalse(string.IsNullOrWhiteSpace(result));
            Assert.IsTrue(result.Contains("arbitrary-nested-value"));
        }
        public void ConvertToDictionaryParametersAndBackSucceeds()
        {
            // Arrange
            var stringProperty            = "arbitrary-string";
            var intProperty               = 42;
            var networkCredentialProperty = new NetworkCredential("arbitrary-user", "arbitrary-password", "arbitrary-domain");

            var arbitraryObject = new ArbitraryObject
            {
                StringProperty            = stringProperty,
                IntProperty               = intProperty,
                NetworkCredentialProperty = networkCredentialProperty
            };

            var sut = new DictionaryParameters();

            // Act
            var resultDictionaryParameters = sut.Convert(arbitraryObject);
            var result = resultDictionaryParameters.Convert <ArbitraryObject>();

            // Assert
            Assert.AreEqual(arbitraryObject.StringProperty, result.StringProperty);
            Assert.AreEqual(arbitraryObject.IntProperty, result.IntProperty);
            Assert.AreEqual(arbitraryObject.NetworkCredentialProperty, result.NetworkCredentialProperty);
        }
        private DictionaryParameters UpdateConfiguration(DictionaryParameters parameters)
        {
            Contract.Requires(parameters.IsValid());

            configuration = parameters;
            return configuration;
        }
        private PowerShellScriptPluginConfiguration UpdateConfiguration(DictionaryParameters parameters)
        {
            Contract.Requires(parameters.IsValid());

            // check for endpoint
            var configurationBase = SchedulerPluginConfigurationBase.Convert<SchedulerPluginConfigurationBase>(parameters);
            Contract.Assert(configurationBase.IsValid());
            
            var configurationManager = new PowerShellScriptPluginConfigurationManager(configurationBase.Endpoints);
            parameters.Add("ComputerName", configurationManager.GetComputerName());
            parameters.Add("ConfigurationName", configurationManager.GetConfigurationNameTemplate());
            parameters.Add("ScriptBase", configurationManager.GetScriptBase());
            parameters.Add("Credential", configurationManager.GetCredentials());

            var message = new StringBuilder();
            message.AppendLine("PowerShellScriptPlugin.UpdatingConfiguration ...");
            message.AppendLine();

            foreach(KeyValuePair<string, object> item in parameters)
            {
                message.AppendFormat("{0}: '{1}'", item.Key, item.Value ?? item.Value.ToString());
                message.AppendLine();
            }
            message.AppendLine();
            message.AppendLine("PowerShellScriptPlugin.UpdatingConfiguration COMPLETED.");
            
            Logger.WriteLine(message.ToString());

            configuration = PowerShellScriptPluginConfiguration.Convert<PowerShellScriptPluginConfiguration>(parameters, true);
            Contract.Assert(configuration.IsValid());

            return configuration;
        }
Exemple #19
0
        public void ConvertFromDictionaryParametersKeyAttributeWithTypeMismatchThrowsArgumentException()
        {
            // Arrange
            var parameters = new DictionaryParameters()
            {
                { DICTIONARY_PARAMETERS_KEY_STRINGPROPERTY, ExpectedStringPropertyDictionaryParametersKey }
                ,
                { DICTIONARY_PARAMETERS_KEY_LONGPROPERTY, "invalid-data-type-for-mapped-proeprty" }
                ,
                { CONVERSION_KEY_STRINGPROPERTY, ExpectedStringPropertyConversionKey }
                ,
                { CONVERSION_KEY_LONGPROPERTY, ExpectedLongPropertyConversionKey }
                ,
                { "StringPropertyNoAttribute", ExpectedStringPropertyNoAttribute }
                ,
                { "LongPropertyNoAttribute", ExpectedLongPropertyNoAttribute }
                ,
                { "StringPropertyRequired", ExpectedStringPropertyRequired }
                ,
                { "LongPropertyRequired", ExpectedLongPropertyRequired }
            };
            var sut = new ConvertibleBaseDtoConverter();

            // Act
            var result = sut.Convert <DictionaryParametersDtoImpl, DictionaryParametersKeyAttribute>(parameters, false);

            // Assert
            // N/A
        }
Exemple #20
0
        public static T Convert <T>(DictionaryParameters dictionaryParameters)
            where T : DictionaryParametersBaseDto, new()
        {
            var result = _converter.Convert <T, DictionaryParametersKeyAttribute>(dictionaryParameters, false);

            return(result);
        }
        public void DictionaryParametersWithRecursion()
        {
            var json = Resources.ACTION_VIRTUALMACHINES_RESPONSE;

            var sut = new DictionaryParameters(json);

            Assert.IsNotNull(sut);
        }
Exemple #22
0
        // this method is provided to facilitate calling from PowerShell
        public static DictionaryParameters Merge(DictionaryParameters left, DictionaryParameters right)
        {
            Contract.Requires(null != left);
            Contract.Requires(null != right);
            Contract.Ensures(null != Contract.Result <DictionaryParameters>());

            return(Merge(left, right, MergeOptions.ThrowOnDuplicateKeys));
        }
        public T Convert <T, TAttribute>(DictionaryParameters dictionaryParameters, bool includeAllProperties)
            where T : ConvertibleBaseDto, new()
            where TAttribute : ConversionKeyBaseAttribute
        {
            Contract.Requires(null != dictionaryParameters);
            Contract.Ensures(null != Contract.Result <T>());

            return(default(T));
        }
        public IList <TBase> Convert <TBase, TAttribute>(DictionaryParameters dictionaryParameters, string nameSpace, bool includeAllProperties)
            where TBase : ConvertibleBaseDto
            where TAttribute : ConversionKeyBaseAttribute
        {
            Contract.Requires(null != dictionaryParameters);
            Contract.Ensures(null != Contract.Result <IList <TBase> >());

            return(default(IList <TBase>));
        }
        public void NullTarget()
        {
            var source = new DictionaryParameters
            {
                { "key1", "valueT1" },
                { "key2", "valueT2" },
            };
            var target = default(DictionaryParameters);

            source.Merge(target);
        }
            public override bool Invoke(DictionaryParameters parameters, IInvocationResult jobResult)
            {
                if(!IsActive)
                {
                    return false;
                }

                jobResult = null;
                
                return true;
            }
        public override bool Initialise(DictionaryParameters parameters, IAppclusivePluginLogger logger, bool activate)
        {
            var result = false;

            result = base.Initialise(parameters, logger, activate);
            if(!configuration.IsValid())
            {
                return result;
            }

            return result;
        }
        private ActivitiPluginConfiguration UpdateConfiguration(DictionaryParameters parameters)
        {
            Contract.Requires(parameters.IsValid());

            // check for endpoint
            var configurationBase = SchedulerPluginConfigurationBase.Convert<SchedulerPluginConfigurationBase>(parameters);
            Contract.Assert(configurationBase.IsValid());
            var endpoints = configurationBase.Endpoints;

            // ManagementUri
            //Type                   : json
            //Value                  : {"ServerUri":"http://www.example.com:9080/activiti-rest/service/"}
            //ManagementCredentialId : 6
            //Id                     : 9
            //Tid                    : ad8f50df-2a5d-4ea5-9fcc-05882f16a9fe
            //Name                   : biz.dfch.PS.Activiti.Client.Setting
            //Description            :
            //CreatedById            : 1
            //ModifiedById           : 1
            //Created                : 12/15/2015 11:46:45 AM +01:00
            //Modified               : 12/15/2015 11:46:45 AM +01:00
            //RowVersion             : {0, 0, 0, 0...}
            //ManagementCredential   :
            //Tenant                 :
            //CreatedBy              :
            //ModifiedBy             :

            var configurationManager = new ActivitiPluginConfigurationManager();

            // get Activiti server
            var managementUri = configurationManager
                .GetManagementUri(endpoints.Core.ManagementUris, configurationManager.GetManagementUriName());
            
            var activitiPluginConfigurationManagementUri = BaseDto
                .DeserializeObject<ActivitiPluginConfigurationManagementUri>(managementUri.Value);
            parameters.Add("ServerBaseUri", activitiPluginConfigurationManagementUri.ServerUri);

            // get Activiti credentials
            var managementCredential = configurationManager
            .GetManagementCredential(endpoints.Core.ManagementCredentials, managementUri.ManagementCredentialId.Value);

            var networkCredential = configurationManager.GetCredential(managementCredential);
            parameters.Add("Credential", networkCredential);

            configuration = ActivitiPluginConfiguration.Convert<ActivitiPluginConfiguration>(parameters, true);
            Contract.Assert(configuration.IsValid());

            // log in to server
            client = new ActivitiClient(configuration.ServerBaseUri, applicationName);
            client.Login(configuration.Credential);

            return configuration;
        }
        public void ConvertToDictionaryParametersThrowsContractException()
        {
            // Arrange
            var arbitraryObject = default(ArbitraryObject);

            var sut = new DictionaryParameters();

            // Act
            var result = sut.Convert(arbitraryObject);

            // Assert
            // N/A
        }
Exemple #30
0
        public static EnvironmentVariableBaseDto Convert(Type type, DictionaryParameters dictionaryParameters, bool includeAllProperties)
        {
            Contract.Requires(null != type);
            Contract.Ensures(null != Contract.Result <EnvironmentVariableBaseDto>());

            var genericMethodInfo = _methodInfoConvertFromDictionary.MakeGenericMethod(type);

            Contract.Assert(null != genericMethodInfo, type.FullName);

            var result = (EnvironmentVariableBaseDto)genericMethodInfo.Invoke(typeof(EnvironmentVariableConverter), new object[] { dictionaryParameters, includeAllProperties });

            return(result);
        }
        public static ConversionKeyBaseDto Convert(Type type, DictionaryParameters dictionaryParameters)
        {
            Contract.Requires(null != type);
            Contract.Ensures(null != Contract.Result <ConversionKeyBaseDto>());

            var genericMethodInfo = _methodInfoConvertFromDictionary.MakeGenericMethod(type);

            Contract.Assert(null != genericMethodInfo, type.FullName);

            var result = (ConversionKeyBaseDto)genericMethodInfo.Invoke(typeof(ConversionKeyConverter), new object[] { dictionaryParameters, false });

            return(result);
        }
Exemple #32
0
        public void ConverterTestWithStringTypesCanBeConvertedAndSucceeds()
        {
            var sut = new DictionaryParameters()
            {
                { ConversionKeyClass.BAG_NAME_INT, "42" }
                ,
                { ConversionKeyClass.BAG_NAME_LONG, (int.MaxValue + 1L).ToString() }
                ,
                { ConversionKeyClass.BAG_NAME_DOUBLE, 4.2d.ToString() }
            };

            var result = ConversionKeyConverter.Convert <ConversionKeyClass>(sut);

            Assert.IsTrue(result.IsValid());
        }
Exemple #33
0
        public void ConverterTestWithMatchingTypesSucceeds()
        {
            var sut = new DictionaryParameters()
            {
                { ConversionKeyClass.BAG_NAME_INT, 42 }
                ,
                { ConversionKeyClass.BAG_NAME_LONG, int.MaxValue + 1L }
                ,
                { ConversionKeyClass.BAG_NAME_DOUBLE, 4.2d }
            };

            var result = ConversionKeyConverter.Convert <ConversionKeyClass>(sut);

            Assert.IsTrue(result.IsValid());
        }
        public void InvokeWithMissingWorkingDirectoryThrowsContractException()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            parameters.Add("CommandLine", "arbitrary-string");
            parameters.Add("missing-parameter-WorkingDirectory", "arbitrary-string");
            parameters.Add("Credential", CredentialCache.DefaultCredentials);
            var jobResult = new JobResult();

            // Act
            var sut = new ProgrammePlugin();
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            // N/A
        }
        public void ConvertFromDictionaryParametersToSchedulerPluginConfigurationBaseSucceeds()
        {
            var uri = new Uri("http://www.example.com/");
            var credentials = CredentialCache.DefaultNetworkCredentials;
            var appclusiveEndpoints = new AppclusiveEndpoints(uri, credentials);

            var sut = new DictionaryParameters();
            sut.Add(typeof(AppclusiveEndpoints).ToString(), appclusiveEndpoints);

            // Act
            var result = SchedulerPluginConfigurationBase.Convert<SchedulerPluginConfigurationBase>(sut);

            // Assert
            Assert.IsTrue(result.IsValid());
            Assert.IsNotNull(result.Endpoints);
        }
        public void NullOnDuplicateKeys()
        {
            var source = new DictionaryParameters
            {
                { "key1", "valueS1" },
                { "key2", "valueS2" },
            };
            var target = new DictionaryParameters
            {
                { "key1", "valueT1" },
                { "key2", "valueT2" },
            };

            var result = source.Merge(target, MergeOptions.NullOnDuplicateKeys);

            Assert.IsNull(result);
        }
        public void GetOrSelfWithInexistentKeyFromDictionaryParametersReturnsDefaultValue()
        {
            // Arrange
            var keyName = "arbitrary-key";
            var value   = "some-arbitrary-string";

            var sut = new DictionaryParameters
            {
                { keyName, value }
            };

            // Act
            var result = sut.GetOrSelf("inexistent-key-name");

            // Assert
            Assert.AreEqual(sut, result);
        }
        public void GetWithInexistentKeyFromDictionaryParametersThrowsContractException()
        {
            // Arrange
            var keyName = "arbitrary-key";
            var value   = "some-arbitrary-string";

            var sut = new DictionaryParameters
            {
                { keyName, value }
            };

            // Act
            var result = sut.Get("inexistent-key-name");

            // Assert
            // N/A
        }
        public void GetOrSelfWithExistentKeyFromDictionaryParametersReturnsValue()
        {
            // Arrange
            var keyName = "arbitrary-key";
            var value   = "some-arbitrary-string";

            var sut = new DictionaryParameters
            {
                { keyName, value }
            };

            // Act
            var result = (string)sut.GetOrSelf(keyName);

            // Assert
            Assert.AreEqual(value, result);
        }
        public void ConvertingFromConversionKeyUtcSucceeds()
        {
            var start = new DateTimeOffset(2016, 4, 1, 1, 2, 3, 0, TimeSpan.FromHours(2));
            var end   = start.AddYears(1).AddMonths(2).AddDays(3).AddHours(4).AddMinutes(5).AddSeconds(6);
            var iso8601DatePeriodUtc = string.Concat(start.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"), "/", end.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz"));

            var parameters = new DictionaryParameters()
            {
                { CONVERSION_KEY_NAME, iso8601DatePeriodUtc }
            };

            var result = ConversionKeyConverter.Convert <ClassWithDateTimeRange>(parameters);

            Assert.AreEqual(iso8601DatePeriodUtc, result.Property.ToString());
            Assert.AreEqual(start, result.Property.Start);
            Assert.AreEqual(end, result.Property.End);
            Assert.AreEqual(end - start, result.Property.TimeSpan);
        }
        public void Initialise(BaseDto configuration, DictionaryParameters parameters)
        {
            Contract.Assert(configuration is PluginLoaderConfiguration);

            var cfg = configuration as PluginLoaderConfiguration;

            // 1. Get folder from where to load extensions
            var extensionsFolder = ConfigurationManager.AppSettings[SchedulerAppSettings.Keys.EXTENSIONS_FOLDER];
            if (!Path.IsPathRooted(extensionsFolder))
            {
                extensionsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, extensionsFolder);
            }
            Contract.Assert(Directory.Exists(extensionsFolder), extensionsFolder);

            cfg.ExtensionsFolder = extensionsFolder;

            // 2. Load plugin names to be loaded
            var pluginTypes = ConfigurationManager.AppSettings[SchedulerAppSettings.Keys.PLUGIN_TYPES];
            
            if(string.IsNullOrWhiteSpace(pluginTypes))
            {
                pluginTypes = biz.dfch.CS.Appclusive.Scheduler.Public.Constants.PLUGIN_TYPE_DEFAULT;
            }

            var pluginTypesToBeLoaded = pluginTypes
                .ToLower()
                .Split(',')
                .Distinct()
                .OrderBy(p => p)
                .ToList();
            Contract.Assert(0 < pluginTypesToBeLoaded.Count());
            
            if(pluginTypesToBeLoaded.Contains(PluginLoader.LOAD_ALL_PATTERN))
            {
                pluginTypesToBeLoaded.Clear();
                pluginTypesToBeLoaded.Add(PluginLoader.LOAD_ALL_PATTERN);
            }
            cfg.PluginTypes = pluginTypesToBeLoaded;

            Trace.WriteLine("SchedulerPluginLoader. ExtensionsFolder: '{0}' (validated). PluginTypes '{1}' (normalised).", cfg.ExtensionsFolder, string.Join(", ", cfg.PluginTypes));
        }
        public void GetAndSetConfigurationSucceeds()
        {
            // Arrange
            var configuration = new DictionaryParameters();
            var key1 = "arbitrary-key1";
            var value1 = "arbitrary-value";
            configuration.Add(key1, value1);
            var key2 = "arbitrary-key2";
            var value2 = 42;
            configuration.Add(key2, value2);
            var key3 = "arbitrary-key3";
            var value3 = new object();
            configuration.Add(key3, value3);

            // Act
            var sut = new DefaultPlugin();
            sut.Configuration = configuration;

            // Assert
            Assert.AreEqual(configuration, sut.Configuration);
        }
        public void InvokeConfigurationSucceeds()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            var key1 = "arbitrary-key1";
            var value1 = "arbitrary-value";
            parameters.Add(key1, value1);
            var key2 = "arbitrary-key2";
            var value2 = 42;
            parameters.Add(key2, value2);
            var key3 = "arbitrary-key3";
            var value3 = new object();
            parameters.Add(key3, value3);

            var jobResult = new JobResult();

            var schedulerPluginBase = Mock.Create<SchedulerPluginBase>();
            Mock.Arrange(() => schedulerPluginBase.Invoke(Arg.IsAny<DictionaryParameters>(), Arg.IsAny<IInvocationResult>()))
                .IgnoreInstance()
                .CallOriginal()
                .MustBeCalled();

            // Act
            var sut = new DefaultPlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Assert.IsTrue(result);
            Assert.IsNotNull(jobResult);
            Assert.IsTrue(jobResult.Description.Contains(key1));
            Assert.IsTrue(jobResult.Description.Contains(value1.ToString()));
            Assert.IsTrue(jobResult.Description.Contains(key2));
            Assert.IsTrue(jobResult.Description.Contains(value2.ToString()));
            Assert.IsTrue(jobResult.Description.Contains(key3));
            Assert.IsTrue(jobResult.Description.Contains(value3.ToString()));

            Mock.Assert(schedulerPluginBase);
        }
        private DictionaryParameters UpdateConfiguration(DictionaryParameters configuration)
        {
            var message = new StringBuilder();
            message.AppendLine("DefaultPlugin.UpdatingConfiguration ...");
            message.AppendLine();

            foreach(KeyValuePair<string, object> item in configuration)
            {
                message.AppendFormat("{0}: '{1}'", item.Key, item.Value ?? item.Value.ToString());
                message.AppendLine();
            }
            message.AppendLine();
            message.AppendLine("DefaultPlugin.UpdatingConfiguration COMPLETED.");
            
            if (null != Logger)
            { 
                Logger.WriteLine("[{0}] {1}", System.Diagnostics.Trace.CorrelationManager.ActivityId, message.ToString());
            }

            this.configuration = configuration;

            return this.configuration;
        }
        public override bool Invoke(DictionaryParameters parameters, IInvocationResult jobResult)
        {
            var fReturn = false;

            if(!IsActive)
            {
                jobResult.Succeeded = fReturn;
                jobResult.Code = 1;
                jobResult.Message = "Plugin inactive";
            }
            
            var invocationParameters = parameters.Convert<ProgrammePluginInvokeParameters>();

            try
            {
                var result = biz.dfch.CS.Utilities.Process.StartProcess(
                    invocationParameters.CommandLine, 
                    invocationParameters.WorkingDirectory, 
                    invocationParameters.Credential);

                fReturn = true;

                jobResult.Succeeded = fReturn;
                jobResult.Code = 0;
                jobResult.Message = invocationParameters.CommandLine;
            }
            catch(Exception ex)
            {
                jobResult.Succeeded = fReturn;
                jobResult.Code = ex.HResult;
                jobResult.Message = ex.Message;
                jobResult.Description = ex.StackTrace;
            }

            return jobResult.Succeeded;
        }
        public void GetConfigurationSucceeds()
        {
            // Arrange
            var configuration = new DictionaryParameters();
            var sut = new ProgrammePlugin();
            sut.Initialise(configuration, new Logger(), true);

            // Act
            configuration = sut.Configuration;

            // Assert
            Assert.AreEqual(configuration, sut.Configuration);
        }
        public override bool Invoke(DictionaryParameters parameters, IInvocationResult jobResult)
        {
            var activityId = Trace.CorrelationManager.ActivityId;
            
            var result = base.Invoke(parameters, jobResult);
            if(!result)
            {
                return result;
            }

            try
            {
                var invocationParameters = parameters.Convert<ActivitiPluginInvokeParameters>();
                var workflowInputParameters = new DictionaryParameters(invocationParameters.Parameters);

                Logger.Info("JobId: '{0}'. ActivityId '{1}'. {2}({3}).", invocationParameters.JobId, activityId, invocationParameters.Id, string.Join(", ", workflowInputParameters.Keys));

                var message = string.Format("JobId: '{0}'", invocationParameters.JobId);
                var description = string.Format("ExternalWorkflow: ActivityId '{0}'.", activityId);

                var definitionId = client.GetDefinitionId(invocationParameters.Id);
                var responseData = client.InvokeWorkflowInstance(definitionId, new Hashtable(workflowInputParameters));
                var responseDataMessage = string.Format
                    (
                    "id '{0}'. processDefinitionId '{1}'. Suspended '{2}'. Completed '{3}'. Ended '{4}'. [JobId '{5}'. ActivityId '{6}]",
                    responseData.id, responseData.processDefinitionId, responseData.suspended, responseData.completed, responseData.ended,
                    invocationParameters.JobId, activityId
                    );
                Logger.Info(responseDataMessage);

                result = true;
                if (result)
                {
                    jobResult.Code = biz.dfch.CS.Appclusive.Scheduler.Public.Constants.InvocationResultCodes.ERROR_SUCCESS;
                }
                else
                {
                    jobResult.Code = biz.dfch.CS.Appclusive.Scheduler.Public.Constants.InvocationResultCodes.ERROR_INVALID_FUNCTION;
                }

                jobResult.Succeeded = result;
                jobResult.Description = description;
                jobResult.Message = message;
            }
            catch(Exception ex)
            {
                jobResult.Succeeded = result;
                jobResult.Code = ex.HResult;
                jobResult.Message = ex.Message;
                jobResult.Description = ex.StackTrace;

                throw;
            }

            return jobResult.Succeeded;
        }
        public ScheduledJobsWorkerConfiguration(IConfigurationLoader loader, string[] args)
        {
            var parameters = new DictionaryParameters();
            if(null != args)
            {
                for(var c = 0; c < args.Count(); c++)
                {
                    var arg = args[c];
                    parameters.Add(string.Format("args{0}", c), arg);
                }
            }

            loader.Initialise(this, parameters);

            return;
        }
        public void LogSucceeds()
        {
            // Arrange
            var client = Mock.Create<ActivitiClient>();
            Mock.Arrange(() => client.Login(Arg.IsAny<NetworkCredential>()))
                .IgnoreInstance()
                .Returns(true)
                .MustBeCalled();

            var managementUriName = SchedulerAppSettings.Keys.EXTERNAL_WORKFLOW_MANAGEMENT_URI_NAME;
            var serverBaseUri = new Uri("http://www.example.com:9080/activiti-rest/service/");
            var managementCredentialId = 5;
            var managementUri = new ManagementUri()
            {
                Id = 42
                ,
                Name = managementUriName
                ,
                ManagementCredentialId = managementCredentialId
                ,
                Value = string.Format("{{\"ServerUri\":\"{0}\"}}", serverBaseUri)
            };

            var encryptedPassword = "******";
            var managementCredential = new ManagementCredential()
            {
                Id = managementCredentialId
                ,
                Name = managementUriName
                ,
                Username = Username
                ,
                Password = Password
                ,
                EncryptedPassword = encryptedPassword
            };

            var activitiPluginConfigurationManager = Mock.Create<ActivitiPluginConfigurationManager>();
            Mock.Arrange(() => activitiPluginConfigurationManager.GetManagementUriName())
                .IgnoreInstance()
                .Returns(managementUriName)
                .MustBeCalled();
            Mock.Arrange(() => activitiPluginConfigurationManager.GetManagementUri(Arg.IsAny<DataServiceQuery<ManagementUri>>(), Arg.IsAny<string>()))
                .IgnoreInstance()
                .Returns(managementUri)
                .MustBeCalled();
            Mock.Arrange(() => activitiPluginConfigurationManager.GetManagementCredential(Arg.IsAny<DataServiceQuery<ManagementCredential>>(), Arg.IsAny<long>()))
                .IgnoreInstance()
                .Returns(managementCredential)
                .MustBeCalled();
            
            var endpoints = Mock.Create<AppclusiveEndpoints>(Constructor.Mocked);
            var apiCore = Mock.Create<Api.Core.Core>(Constructor.Mocked);
            endpoints.Core = apiCore;
            var parameters = new DictionaryParameters();
            parameters.Add(typeof(AppclusiveEndpoints).ToString(), endpoints);

            var message = "arbitrary-message";
            var logger = new Logger();
            var sut = new ActivitiPlugin();

            sut.Initialise(parameters, logger, true);

            // Act
            sut.Logger.WriteLine(message);

            // Assert
            Mock.Assert(client);
            Mock.Assert(activitiPluginConfigurationManager);
        }
        public ScheduledJobsWorker(ScheduledJobsWorkerConfiguration configuration)
        {
            Contract.Requires(configuration.IsValid());

            this.configuration = configuration;

            Trace.WriteLine(Method.fn());

            var result = false;

            try
            {
                Trace.WriteLine("Uri: '{0}'", configuration.Uri.AbsoluteUri, "");

                // connect to Appclusive server
                var baseUri = new Uri(string.Format("{0}api", configuration.Uri.AbsoluteUri));
                endpoints = new AppclusiveEndpoints(baseUri, configuration.Credential);

                // initialise each plugin
                foreach (var plugin in configuration.Plugins)
                {
                    try
                    {
                        Trace.WriteLine("Initialising plugin '{0}' [{1}, {2}] ...", plugin.Metadata.Type, plugin.Metadata.Role, plugin.Metadata.Priority);

                        var pluginParameters = new DictionaryParameters
                        {
                            {typeof(AppclusiveEndpoints).ToString(), endpoints}
                        };
                        plugin.Value.Initialise(pluginParameters, configuration.Logger, true);

                        Trace.WriteLine
                        (
                            "Initialising plugin '{0}' [{1}, {2}] COMPLETED. IsInitialised {3}. IsActive {4}."
                            , 
                            plugin.Metadata.Type, plugin.Metadata.Role, plugin.Metadata.Priority
                            ,
                            plugin.Value.IsInitialised, plugin.Value.IsActive
                        );
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format("Initialising plugin '{0}' [{1}, {2}] FAILED.", plugin.Metadata.Type, plugin.Metadata.Role, plugin.Metadata.Priority);
                        Trace.WriteException(message, ex);
                    }
                }

                // get all defined scheduled jobs for all tenants (based on credentials)
                result = GetScheduledJobs();

                // create the timer to process all scheduled jobs periodically
                stateTimer = new ScheduledJobsWorkerTimerFactory().CreateTimer(new TimerCallback(RunJobs), null, 1000, 1000 * 60);
            }
            catch (Exception ex)
            {
                Trace.WriteException(ex.Message, ex);
                throw;
            }

            this.isInitialised = result;
            this.IsActive = result;
        
            return;
        }
        public void SetConfigurationSucceeds()
        {
            // Arrange
            var configuration = new DictionaryParameters();

            // Act
            var sut = new ProgrammePlugin();
            sut.Configuration = configuration;

            // Assert
            Assert.AreEqual(configuration, sut.Configuration);
        }
        public void InvokeWithInvalidTypeCredentialThrowsContractException()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            parameters.Add("CommandLine", "arbitrary-string");
            parameters.Add("WorkingDirectory", "arbitrary-string");
            parameters.Add("Credential", new object());
            var jobResult = new JobResult();

            // Act
            var sut = new ProgrammePlugin();
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            // N/A
        }
        public void InitialiseSucceeds()
        {
            // Arrange
            var client = Mock.Create<ActivitiClient>();
            Mock.Arrange(() => client.Login(Arg.IsAny<NetworkCredential>()))
                .IgnoreInstance()
                .Returns(true)
                .MustBeCalled();

            var serverBaseUri = new Uri("http://www.example.com:9080/activiti-rest/service/");
            var managementCredentialId = 5;
            var managementUriName = SchedulerAppSettings.Keys.EXTERNAL_WORKFLOW_MANAGEMENT_URI_NAME;
            var managementUri = new ManagementUri()
            {
                Id = 42
                ,
                Name = managementUriName
                ,
                ManagementCredentialId = managementCredentialId
                ,
                Value = string.Format("{{\"ServerUri\":\"{0}\"}}", serverBaseUri)
            };
            var managementUris = new List<ManagementUri>()
            {
                managementUri
            };

            var dataServiceQueryManagementUris = Mock.Create<DataServiceQuery<ManagementUri>>();
            Mock.Arrange(() => dataServiceQueryManagementUris.Where(e => e.Name == managementUriName))
                .IgnoreInstance()
                .Returns(managementUris.AsQueryable())
                .MustBeCalled();

            var encryptedPassword = "******";
            var managementCredential = new ManagementCredential()
            {
                Id = managementCredentialId
                ,
                Name = managementUriName
                ,
                Username = Username
                ,
                Password = Password
                ,
                EncryptedPassword = encryptedPassword
            };
            var managementCredentials = new List<ManagementCredential>()
            {
                managementCredential
            };

            var dataServiceQueryManagementCredentials = Mock.Create<DataServiceQuery<ManagementCredential>>();
            Mock.Arrange(() => dataServiceQueryManagementCredentials.Where(e => e.Id == managementCredentialId))
                .IgnoreInstance()
                .Returns(managementCredentials.AsQueryable())
                .MustBeCalled();

            var endpoints = Mock.Create<AppclusiveEndpoints>(Constructor.Mocked);
            var apiCore = Mock.Create<Api.Core.Core>(Constructor.Mocked);
            endpoints.Core = apiCore;
            var parameters = new DictionaryParameters();
            parameters.Add(typeof(AppclusiveEndpoints).ToString(), endpoints);
            
            Mock.SetupStatic(typeof(ConfigurationManager));
            Mock.Arrange(() => ConfigurationManager.AppSettings[Arg.IsAny<string>()])
                .Returns(managementUriName)
                .MustBeCalled();

            var logger = new Logger();

            var sut = new ActivitiPlugin();

            // Act
            var result = sut.Initialise(parameters, logger, true);

            // Assert
            Mock.Assert(() => ConfigurationManager.AppSettings[Arg.IsAny<string>()]);
            Mock.Assert(client);

            Assert.IsTrue(result);
            Assert.IsTrue(sut.IsInitialised);
            Assert.IsTrue(sut.IsActive);
        }
        public void InvokeFails()
        {
            // Arrange
            var commandLine = "arbitrary-string";
            var workingDirectory = "arbitrary-string";
            var credential = new NetworkCredential("arbitrary-user", "arbitrary-password", "arbitrary-domain");
            var parameters = new DictionaryParameters();
            parameters.Add("JobId", 42);
            parameters.Add("CommandLine", commandLine);
            parameters.Add("WorkingDirectory", workingDirectory);
            parameters.Add("Credential", credential);
            var jobResult = new JobResult();

            Mock.SetupStatic(typeof(biz.dfch.CS.Utilities.Process));

            Mock.Arrange(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine),
                    Arg.Is<string>(workingDirectory),
                    Arg.Is<NetworkCredential>(credential))
                )
                .Throws<InvalidOperationException>()
                .OccursOnce();

            // Act
            var sut = new ProgrammePlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Mock.Assert(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                );
            Assert.IsFalse(result);
            Assert.IsFalse(jobResult.Succeeded);
            Assert.AreNotEqual(0, jobResult.Code);
            Assert.IsFalse(string.IsNullOrWhiteSpace(jobResult.Message));
            Assert.IsFalse(string.IsNullOrWhiteSpace(jobResult.Description));
        }
        public void InvokeJobResultNullOnReturnThrowsContractException()
        {
            // Arrange
            var sut = new SchedulerPluginImpl();
            var parameters = new DictionaryParameters();
            var jobResult = new JobResult();

            // Act
            sut.Invoke(parameters, jobResult);

            // Assert
            Assert.Fail("CodeContracts are not enabled.");
        }
        public void InvokeSucceeds()
        {
            // Arrange
            var commandLine = "arbitrary-string";
            var workingDirectory = "arbitrary-string";
            var credential = new NetworkCredential("arbitrary-user", "arbitrary-password", "arbitrary-domain");
            var parameters = new DictionaryParameters();
            parameters.Add("JobId", 42);
            parameters.Add("CommandLine", commandLine);
            parameters.Add("WorkingDirectory", workingDirectory);
            parameters.Add("Credential", credential);
            var jobResult = new JobResult();

            Mock.SetupStatic(typeof(biz.dfch.CS.Utilities.Process));

            Mock.Arrange(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                )
                .Returns(default(Dictionary<string, string>))
                .OccursOnce();

            // Act
            var sut = new ProgrammePlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Mock.Assert(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                );
            Assert.IsTrue(result);
            Assert.IsTrue(jobResult.Succeeded);
            Assert.AreEqual(0, jobResult.Code);
        }
        public void InvokeWorkflowSucceeds()
        {
            // Arrange
            //var definitionKey = "arbitrary-process-definition-id";
            var definitionKey = "com.swisscom.cms.agentbasedbackup.backupjob.v002.CheckBackupStatus";
            var parameters = new DictionaryParameters()
            {
                { "nodeId", 12345 }
            };
            var sut = new ActivitiClient(environment.ServerBaseUri, environment.ApplicationName);
            sut.Login(environment.Credential);
            var definitionId = sut.GetDefinitionId(definitionKey);

            // Act
            var result = sut.InvokeWorkflowInstance(definitionId, new System.Collections.Hashtable(parameters));

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.id);
            Assert.IsNotNull(result.processDefinitionId);
            Assert.IsNotNull(result.ended);
            Assert.IsNotNull(result.completed);
            Assert.IsNotNull(result.suspended);
        }
        public void UpdateConfigurationSucceeds()
        {
            // Arrange
            Mock.SetupStatic(typeof(ConfigurationManager));
            Mock.Arrange(() => ConfigurationManager.AppSettings[Arg.IsAny<string>()])
                .Returns(SchedulerAppSettings.Keys.EXTERNAL_WORKFLOW_MANAGEMENT_URI_NAME)
                .MustBeCalled();

            var client = Mock.Create<ActivitiClient>();
            Mock.Arrange(() => client.Login(Arg.IsAny<NetworkCredential>()))
                .IgnoreInstance()
                .Returns(true)
                .MustBeCalled();

            var serverBaseUri = new Uri("http://www.example.com:9080/activiti-rest/service/");
            var managementCredentialId = 5;
            var managementUriName = SchedulerAppSettings.Keys.EXTERNAL_WORKFLOW_MANAGEMENT_URI_NAME;
            var managementUri = new ManagementUri()
            {
                Id = 42
                ,
                Name = managementUriName
                ,
                ManagementCredentialId = managementCredentialId
                ,
                Value = string.Format("{{\"ServerUri\":\"{0}\"}}", serverBaseUri)
            };
            var managementUris = new List<ManagementUri>()
            {
                managementUri
            };

            var dataServiceQueryManagementUris = Mock.Create<DataServiceQuery<ManagementUri>>();
            Mock.Arrange(() => dataServiceQueryManagementUris.Where(e => e.Name == managementUriName))
                .IgnoreInstance()
                .Returns(managementUris.AsQueryable())
                .MustBeCalled();

            var encryptedPassword = "******";
            var managementCredential = new ManagementCredential()
            {
                Id = managementCredentialId
                ,
                Name = managementUriName
                ,
                Username = Username
                ,
                Password = Password
                ,
                EncryptedPassword = encryptedPassword
            };
            var managementCredentials = new List<ManagementCredential>()
            {
                managementCredential
            };

            var dataServiceQueryManagementCredentials = Mock.Create<DataServiceQuery<ManagementCredential>>();
            Mock.Arrange(() => dataServiceQueryManagementCredentials.Where(e => e.Id == managementCredentialId))
                .IgnoreInstance()
                .Returns(managementCredentials.AsQueryable())
                .MustBeCalled();

            var endpoints = Mock.Create<AppclusiveEndpoints>(Constructor.Mocked);
            var apiCore = Mock.Create<Api.Core.Core>(Constructor.Mocked);
            endpoints.Core = apiCore;
            var parameters = new DictionaryParameters();
            parameters.Add(typeof(AppclusiveEndpoints).ToString(), endpoints);

            var sut = new ActivitiPlugin();
            Mock.NonPublic.Arrange<string>(sut, "managementUriName")
                .IgnoreInstance()
                .Returns(managementUriName);

            // Act
            sut.Configuration = parameters;

            // Assert
            Mock.Arrange(() => ConfigurationManager.AppSettings[Arg.IsAny<string>()]);
            Mock.Assert(client);
            Mock.Assert(endpoints);
            Mock.Assert(dataServiceQueryManagementUris);
            Mock.Assert(dataServiceQueryManagementCredentials);

            Assert.IsTrue(sut.Configuration.ContainsKey("ServerBaseUri"));
            var actualServerBaseUri = sut.Configuration["ServerBaseUri"] as Uri;
            Assert.IsNotNull(actualServerBaseUri);
            Assert.AreEqual(serverBaseUri, actualServerBaseUri);

            Assert.IsTrue(sut.Configuration.ContainsKey("Credential"));
            var actualCredential = sut.Configuration["Credential"] as NetworkCredential;
            Assert.IsNotNull(actualCredential);
            Assert.AreEqual(Username, actualCredential.UserName);
            Assert.AreEqual(Password, actualCredential.Password);
        }
        public void ConvertDictionaryParametersToHashtableSucceeds()
        {
            var key = "nodeId";
            var value = 12345;
            var parameters = new DictionaryParameters()
            {
                { key, value }
            };

            var hashtable = new Hashtable(parameters);

            Assert.IsTrue(hashtable.ContainsKey(key));
            Assert.AreEqual(value, hashtable[key]);
        }
        public override bool Invoke(DictionaryParameters parameters, IInvocationResult invocationResult)
        {
            Contract.Requires("2" == invocationResult.Version, "This plugin only supports non-serialisable invocation results.");

            var fReturn = false;

            var result = base.Invoke(parameters, invocationResult);
            if(!result)
            {
                return result;
            }

            var message = new StringBuilder();
            message.AppendLine("PowerShellScriptPlugin.Invoke ...");
            message.AppendLine();

            Logger.WriteLine(message.ToString());
            message.Clear();

            Contract.Assert(parameters.ContainsKey(SCRIPT_NAME_KEY));
            var scriptPathAndName = parameters.GetOrDefault(SCRIPT_NAME_KEY, "") as string;
            parameters.Remove(SCRIPT_NAME_KEY);
            Contract.Assert(!parameters.ContainsKey(SCRIPT_NAME_KEY));

            var scriptParameters = (Dictionary<string, object>) parameters;
            Contract.Assert(null != scriptParameters);

            var activityId = Trace.CorrelationManager.ActivityId;

            foreach(var item in scriptParameters)
            {
                message.AppendFormat("{0} - {1}", item.Key, item.Value);
                message.AppendLine();
            }
            Logger.WriteLine(message.ToString());
            message.Clear();

            var data = new ThreadPoolUserWorkItemParameters()
            {
                ActivityId = activityId
                ,
                Logger = Logger
                ,
                ScriptParameters = scriptParameters
                ,
                ScriptPathAndName = scriptPathAndName
            };
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolUserWorkItem.ThreadProc), data);

            message.AppendLine("PowerShellScriptPlugin.Invoke DISPATCHED.");
            message.AppendLine();
            
            Logger.WriteLine(message.ToString());

            fReturn = true;
            
            invocationResult.Succeeded = fReturn;
            invocationResult.Code = 1;
            invocationResult.Message = "PowerShellScriptPlugin.Invoke COMPLETED and logged the intended operation to a tracing facility.";
            invocationResult.Description = message.ToString();
            invocationResult.InnerJobResult = null;

            return fReturn;
        }