Exemplo n.º 1
0
        public BugTracer(ProviderName providername,string connString)
        {
            if (!ConnStringManager.SetConnection(providername, connString))
            {
                throw new ApplicationException(RM.GetString(""));
            }

            this.ApplicationProvider = new ApplicationRepository();
            this.BugProvider = new BugRepository();
        }
Exemplo n.º 2
0
        public static bool SetConnection(ProviderName providerName,string connString)
        {
            bool rv=false;
            ConnectionStringSettings setting = new ConnectionStringSettings();
            setting.Name = Guid.NewGuid().ToString() + "_Db";
            setting.ProviderName = providerName.GetStringValue();
            setting.ConnectionString = connString;

            ConfigurationManager.ConnectionStrings.Add(setting);
            connStringName = setting.Name;
            var cString = ConfigurationManager.ConnectionStrings[connStringName].ToString();

            if (TestConnect(cString))
                return true;
            return rv;
        }
        private SqlContext Initialize()
        {
            _logger.LogDebug("Initializing.");

            if (ConnectionString.IsNullOrWhiteSpace())
            {
                throw new InvalidOperationException("The factory has not been configured with a proper connection string.");
            }

            if (ProviderName.IsNullOrWhiteSpace())
            {
                throw new InvalidOperationException("The factory has not been configured with a proper provider name.");
            }

            if (DbProviderFactory == null)
            {
                throw new Exception($"Can't find a provider factory for provider name \"{ProviderName}\".");
            }

            _databaseType = DatabaseType.Resolve(DbProviderFactory.GetType().Name, ProviderName);
            if (_databaseType == null)
            {
                throw new Exception($"Can't find an NPoco database type for provider name \"{ProviderName}\".");
            }

            _sqlSyntax = _dbProviderFactoryCreator.GetSqlSyntaxProvider(ProviderName !);
            if (_sqlSyntax == null)
            {
                throw new Exception($"Can't find a sql syntax provider for provider name \"{ProviderName}\".");
            }

            _bulkSqlInsertProvider = _dbProviderFactoryCreator.CreateBulkSqlInsertProvider(ProviderName !);

            _databaseType = _sqlSyntax.GetUpdatedDatabaseType(_databaseType, ConnectionString);

            // ensure we have only 1 set of mappers, and 1 PocoDataFactory, for all database
            // so that everything NPoco is properly cached for the lifetime of the application
            _pocoMappers = new NPoco.MapperCollection();
            // add all registered mappers for NPoco
            _pocoMappers.AddRange(_npocoMappers);

            _pocoMappers.AddRange(_dbProviderFactoryCreator.ProviderSpecificMappers(ProviderName !));

            var factory = new FluentPocoDataFactory(GetPocoDataFactoryResolver, _pocoMappers);

            _pocoDataFactory = factory;
            var config = new FluentConfig(xmappers => factory);

            // create the database factory
            _npocoDatabaseFactory = DatabaseFactory.Config(cfg =>
            {
                cfg.UsingDatabase(CreateDatabaseInstance) // creating UmbracoDatabase instances
                .WithFluentConfig(config);                // with proper configuration

                foreach (IProviderSpecificInterceptor interceptor in _dbProviderFactoryCreator.GetProviderSpecificInterceptors(ProviderName !))
                {
                    cfg.WithInterceptor(interceptor);
                }
            });

            if (_npocoDatabaseFactory == null)
            {
                throw new NullReferenceException("The call to UmbracoDatabaseFactory.Config yielded a null UmbracoDatabaseFactory instance.");
            }

            _logger.LogDebug("Initialized.");

            return(new SqlContext(_sqlSyntax, _databaseType, _pocoDataFactory, _mappers));
        }
Exemplo n.º 4
0
 public void Create_beer_provider_with_null_beer_should_raise_an_exception()
 {
     var provider     = new Provider(ProviderName.Create("GeneDrinks").Value);
     var beerProvider = new BeerProvider(BeerProviderQuantity.Create(10).Value, null, provider);
 }
Exemplo n.º 5
0
 public static Provider GetProvider(ProviderName name)
 {
     if (_Providers.ContainsKey(name)) return _Providers[name];
     return null;
 }
Exemplo n.º 6
0
        public override int GetHashCode()
        {
            var hash = ProviderName.GetHashCode();

            return(ScheduleIntervalDefinitions.Aggregate(hash, (currentHash, definition) => (hash * 397) ^ definition.GetHashCode()));
        }
Exemplo n.º 7
0
 public override int GetHashCode()
 {
     return(ProviderName.GetHashCode() ^ TheCultureInfo.GetHashCode());
 }
Exemplo n.º 8
0
        public override bool GenerateDynamicParameters()
        {
            var thisIsFirstObject = false;

            try {
                if (!IsReentrantLocked)
                {
                    // we're not locked at this point. Let's turn on the lock.
                    IsReentrantLocked = true;
                    thisIsFirstObject = true;

                    try {
                        // do all the work that we need to during the lock
                        // this includes:
                        //      one-time-per-call work
                        //      any access to MyInvocation.MyCommand.*
                        //      modifying parameter validation sets
                        //

                        if (MyInvocation != null && MyInvocation.MyCommand != null && MyInvocation.MyCommand.Parameters != null)
                        {
                            GetType().AddOrSet(MyInvocation.MyCommand.Parameters, "MyInvocation.MyCommand.Parameters");
                        }
#if DEEP_DEBUG
                        else
                        {
                            if (MyInvocation == null)
                            {
                                Console.WriteLine("»»» Attempt to get parameters MyInvocation == NULL");
                            }
                            else
                            {
                                if (MyInvocation.MyCommand == null)
                                {
                                    Console.WriteLine("»»» Attempt to get parameters MyCommand == NULL");
                                }
                                else
                                {
                                    Console.WriteLine("»»» Attempt to get parameters Parameters == NULL");
                                }
                            }
                        }
#endif


                        // the second time, it will generate all the parameters, including the dynamic ones.
                        // (not that we currently need it, but if you do, you gotta do it here!)
                        // var all_parameters = MyInvocation.MyCommand.Parameters;

                        // ask for the unbound arguments.
                        var unbound = UnboundArguments;
                        if (unbound.ContainsKey("ProviderName") || unbound.ContainsKey("Provider"))
                        {
                            var pName = unbound.ContainsKey("ProviderName")?unbound["ProviderName"]:unbound["Provider"];
                            if (pName != null)
                            {
                                if (pName.GetType().IsArray)
                                {
                                    ProviderName = pName as string[] ?? (((object[])pName).Select(p => p.ToString()).ToArray());
                                }
                                else
                                {
                                    ProviderName = new[] { pName.ToString() };
                                }

                                // a user specifies -providerName
                                _isUserSpecifyOneProviderName = (ProviderName.Count() == 1);
                            }
                        }

                        // we've now got a copy of the arguments that aren't bound
                        // and we can potentially narrow the provider selection based
                        // on arguments the user specified.

                        if (null == CachedSelectedProviders || IsFailingEarly || IsCanceled)
                        {
#if DEEP_DEBUG
                            Console.WriteLine("»»» Cancelled before we got finished doing dynamic parameters");
#endif
                            // this happens if there is a serious failure early in the cmdlet
                            // i.e. - if the SelectedProviders comes back empty (due to agressive filtering)

                            // in this case, we just want to provide a catch-all for remaining arguments so that we can make
                            // output the error that we really want to (that the user specified conditions that filtered them all out)

                            DynamicParameterDictionary.Add("RemainingArguments", new RuntimeDefinedParameter("RemainingArguments", typeof(object), new Collection <Attribute> {
                                new ParameterAttribute()
                                {
                                    ValueFromRemainingArguments = true
                                },
                            }));
                        }

                        // at this point, we're actually calling to have the dynamic parameters generated
                        // that are expected to be used.
                        return(ActualGenerateDynamicParameters(unbound));
                    } finally {
                        IsReentrantLocked = false;
                    }
                }

                // otherwise just call the AGDP because we're in a reentrant call.
                // and this might be needed if the original call had some strange need
                // to know what the parameters that it's about to generate would be.
                // Yeah, you heard me.
                return(ActualGenerateDynamicParameters(null));
            } finally
            {
                if (thisIsFirstObject)
                {
                    // clean up our once-per-call data.
                    GetType().Remove <PackageProvider[]>("CachedSelectedProviders");
                    GetType().Remove <Dictionary <string, ParameterMetadata> >("MyInvocation.MyCommand.Parameters");
                    GetType().Remove <DynamicOption[]>("CachedDynamicOptions");
                }
            }
            // return true;
        }
        public DataTable getDataTable(string StrSqlCommand, string StrStringConnection, ProviderName ProviderName)
        {
            try
            {
                switch (ProviderName)
                {
                    case ProviderName.SQLServer:
                        #region SQL Server
                        using (SqlConnection conn = new SqlConnection(StrStringConnection))
                        {
                            conn.Open();

                            using (SqlDataAdapter da = new SqlDataAdapter(StrSqlCommand, conn))
                            {
                                using (DataSet ds = new DataSet())
                                {
                                    da.Fill(ds); conn.Close();
                                    return ds.Tables[0];
                                }
                            }
                        }
                        #endregion
                    case ProviderName.MySQL:
                        #region MsSQL
                        //using (MySqlConnection conn = new MySqlConnection(StrStringConnection))
                        //{
                        //    conn.Open();

                        //    using (MySqlDataAdapter da = new MySqlDataAdapter(StrSqlCommand, conn))
                        //    {
                        //        using (DataSet ds = new DataSet())
                        //        {
                        //            da.Fill(ds); conn.Close();
                        //            return ds.Tables[0];
                        //        }
                        //    }
                        //}
                        #endregion
                    case ProviderName.Oracle:
                        #region Oracle
                        //using (OracleConnection conn = new OracleConnection(StrStringConnection))
                        //{
                        //    conn.Open();

                        //    using (OracleDataAdapter da = new OracleDataAdapter(StrSqlCommand, conn))
                        //    {
                        //        using (DataSet ds = new DataSet())
                        //        {
                        //            da.Fill(ds); conn.Close();
                        //            return ds.Tables[0];
                        //        }
                        //    }
                        //}
                        #endregion
                    default:
                        return null;
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates an accurate AzureRM resource Uri string
        /// </summary>
        /// <returns>AzureRM resource Uri String</returns>
        public override string ToString()
        {
            if (!IsValid)
            {
                throw new Exception("ResourceUri does not contain valid components to create a valid AzureRM resource Uri string.");
            }

            // test & cleanup
            string?providerName      = (string.IsNullOrWhiteSpace(ProviderName) ? null : ProviderName.Trim());
            string?type              = (string.IsNullOrWhiteSpace(Type) ? null : Type.Trim());
            string?resourceGroupName = (string.IsNullOrWhiteSpace(ResourceGroupName) ? null : ResourceGroupName.Trim());
            string?objectName        = (string.IsNullOrWhiteSpace(ResourceName) ? null : ResourceName.Trim());

            StringBuilder uri = new StringBuilder();

            uri.Append("/subscriptions/").Append(Subscription.ToString("d"));

            if (resourceGroupName != null)
            {
                uri.Append("/resourceGroups/").Append(resourceGroupName);
            }

            if (providerName != null)
            {
                uri.Append("/providers/").Append(providerName);
            }

            if (type != null)
            {
                uri.Append("/").Append(type);
            }

            if (objectName != null)
            {
                uri.Append("/").Append(objectName);
            }

            return(uri.ToString());
        }
        public bool Execute(string StrSqlCommand, string StrStringConnection, ProviderName ProviderName)
        {
            try
            {
                switch (ProviderName)
                {
                    case ProviderName.SQLServer:
                        #region SQL Server
                        using (SqlConnection conn = new SqlConnection(StrStringConnection))
                        {
                            conn.Open();

                            using (SqlCommand cmd = new SqlCommand(StrSqlCommand, conn))
                            {
                                using (SqlDataReader dr = cmd.ExecuteReader())
                                {
                                    conn.Close();
                                    return true;
                                }
                            }
                        }
                        #endregion
                    case ProviderName.MySQL:
                        #region MsSQL
                        //using (MySqlConnection conn = new MySqlConnection(StrStringConnection))
                        //{
                        //    conn.Open();

                        //    using (MySqlCommand cmd = new MySqlCommand(StrSqlCommand, conn))
                        //    {
                        //        using (MySqlDataReader dr = cmd.ExecuteReader())
                        //        {
                        //            conn.Close();
                        //            return true;
                        //        }
                        //    }
                        //}
                        #endregion
                    case ProviderName.Oracle:
                        #region Oracle
                        //using (OracleConnection conn = new OracleConnection(StrStringConnection))
                        //{
                        //    conn.Open();

                        //    using (OracleCommand cmd = new OracleCommand(StrSqlCommand, conn))
                        //    {
                        //        using (OracleDataReader dr = cmd.ExecuteReader())
                        //        {
                        //            conn.Close();
                        //            return true;
                        //        }
                        //    }
                        //}
                        #endregion
                    default:
                        return false;
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
 public DataClass(ProviderName DataBaseName)
 {
     _providerName = DataBaseName.ToString();
 }
        private string getStringConnection(string StringConnection)
        {
            string strcnx = "";

            try
            {
                strcnx = ConfigurationManager.ConnectionStrings[StringConnection].ConnectionString;
                _providerName = ConfigurationManager.ConnectionStrings[StringConnection].ProviderName;

                if (_providerName != null)
                {
                    switch (_providerName)
                    {
                        case "System.Data.SqlClient":
                            _DataBaseName = ProviderName.SQLServer;
                            break;
                        case "MySql.Data.MySqlClient":
                            _DataBaseName = ProviderName.MySQL;
                            break;
                        case "System.Data.OracleClient":
                            _DataBaseName = ProviderName.Oracle;
                            break;
                    }
                }
                else
                    throw e;
            }
            catch
            {
                if (_providerName == null)
                    throw new Exception("O provedor de banco de dados não foi informado! Talvez esteja faltando passar o parametro na sobrecarga do construtor da classe ou do método com o nome do provedor de banco de dados.", e);
                else
                {
                    strcnx = StringConnection;

                    switch (_providerName)
                    {
                        case "SQLServer":
                            _DataBaseName = ProviderName.SQLServer;
                            break;
                        case "MySQL":
                            _DataBaseName = ProviderName.MySQL;
                            break;
                        case "Oracle":
                            _DataBaseName = ProviderName.Oracle;
                            break;
                    }
                }
            }
            return strcnx;
        }
Exemplo n.º 14
0
        void Initializer()
        {
            string[] items = ConnectionString.Split(';');
            foreach (var item in items)
            {
                string[] keyValue = item.Split('=');
                if (keyValue.Length == 2)
                {
                    string key = keyValue[0].Trim().ToLower();
                    string val = keyValue[1].Trim();
                    if ("server".Equals(key, StringComparison.Ordinal) ||
                        "data source".Equals(key, StringComparison.Ordinal))
                    {
                        DataSource = val;
                        continue;
                    }
                    if ("charset".Equals(key, StringComparison.Ordinal))
                    {
                        CharSet = val;
                        continue;
                    }
                    if ("database".Equals(key, StringComparison.Ordinal) ||
                        "initial catalog".Equals(key, StringComparison.Ordinal))
                    {
                        DatabaseName = val;
                        DbLevel      = DbLevel.UnKown;
                        val          = val.ToLower();
                        if (val.IndexOf("config", StringComparison.Ordinal) != -1)
                        {
                            DbLevel = DbLevel.Config;
                        }
                        else if (val.IndexOf("data", StringComparison.Ordinal) != -1)
                        {
                            DbLevel = DbLevel.Game;
                        }
                        else if (val.IndexOf("log", StringComparison.Ordinal) != -1)
                        {
                            DbLevel = DbLevel.Log;
                        }
                        continue;
                    }
                }
            }

            if ("localsqlserver".Equals(ProviderName.ToLower(), StringComparison.Ordinal))
            {
                ProviderTypeName = "SqlDataProvider";
                DbLevel          = DbLevel.LocalSql;
            }
            else if ("localmysqlserver".Equals(ProviderName.ToLower(), StringComparison.Ordinal))
            {
                ProviderTypeName = "MySqlDataProvider";
                DbLevel          = DbLevel.LocalMySql;
            }

            if (ProviderType == DbProviderType.MySql)
            {
                if (string.IsNullOrEmpty(CharSet))
                {
                    CharSet = "gbk";
                    string charset = string.Format("CharSet={0};", CharSet);
                    ConnectionString += ConnectionString.EndsWith(";") ? charset : ";" + charset;
                }
            }
        }
 public override int GetHashCode()
 {
     return(ProviderName.GetHashCode());
 }
Exemplo n.º 16
0
        public override bool ProcessRecordAsync()
        {
            if (IsSourceByObject)
            {
                foreach (var source in InputObject)
                {
                    if (Stopping)
                    {
                        return(false);
                    }

                    var provider = SelectProviders(source.ProviderName).FirstOrDefault();
                    if (provider == null)
                    {
                        if (string.IsNullOrEmpty(source.ProviderName))
                        {
                            return(Error(Constants.Errors.UnableToFindProviderForSource, source.Name));
                        }
                        return(Error(Constants.Errors.UnknownProvider, source.ProviderName));
                    }
                    Unregister(source);
                }
                return(true);
            }

            // otherwise, we're just deleting a source by name
            var prov = SelectedProviders.ToArray();

            if (Stopping)
            {
                return(false);
            }

            if (prov.Length == 0)
            {
                if (ProviderName.IsNullOrEmpty() || string.IsNullOrEmpty(ProviderName[0]))
                {
                    return(Error(Constants.Errors.UnableToFindProviderForSource, Source ?? Location));
                }
                return(Error(Constants.Errors.UnknownProvider, ProviderName[0]));
            }

            if (prov.Length > 0)
            {
                var sources = prov.SelectMany(each => each.ResolvePackageSources(SuppressErrorsAndWarnings).Where(source => source.IsRegistered && (source.Name.EqualsIgnoreCase(Source) || source.Location.EqualsIgnoreCase(Source))).ToArray()).ToArray();

                if (sources.Length == 0)
                {
                    return(Error(Constants.Errors.SourceNotFound, Source));
                }

                if (sources.Length > 1)
                {
                    return(Error(Constants.Errors.SourceFoundInMultipleProviders, Source, prov.Select(each => each.ProviderName).JoinWithComma()));
                }

                return(Unregister(sources[0]));
            }

            return(true);
        }
 public DataClass(string StringConnection, ProviderName DataBaseName)
 {
     _providerName = DataBaseName.ToString();
     _StringConnection = getStringConnection(StringConnection);
 }
Exemplo n.º 18
0
        public void Verify(string description = null, string providerState = null)
        {
            if (String.IsNullOrEmpty(PactFileUri))
            {
                throw new InvalidOperationException(
                          "PactFileUri has not been set, please supply a uri using the PactUri method.");
            }

            MessagePactFile pactFile;

            try
            {
                string pactFileJson;

                if (IsWebUri(PactFileUri))
                {
                    //Pact broker does not handle v3 specs for messages at this time
                    throw new NotImplementedException(
                              "Pact broker does not handle v3 specs for messages at this time.  Use a local pact file uri.");
                }

                pactFileJson = File.ReadAllText(PactFileUri);

                pactFile = JsonConvert.DeserializeObject <MessagePactFile>(pactFileJson);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                          String.Format("Json Pact file could not be retrieved using uri \'{0}\'.", PactFileUri), ex);
            }

            //Filter interactions
            if (description != null)
            {
                pactFile.Messages = pactFile.Messages.Where(x => x.Description.Equals(description));
            }

            if (providerState != null)
            {
                pactFile.Messages = pactFile.Messages.Where(x => x.ProviderState.Equals(providerState));
            }

            if ((description != null || providerState != null) &&
                (pactFile.Messages == null || !pactFile.Messages.Any()))
            {
                throw new ArgumentException(
                          "The specified description and/or providerState filter yielded no interactions.");
            }

            var loggerName = LogProvider.CurrentLogProvider.AddLogger(pactVerifierConfig.LogDir,
                                                                      ProviderName.ToLowerSnakeCase(), "{0}_verifier.log");

            pactVerifierConfig.LoggerName = loggerName;

            try
            {
                var validator = new MessageProviderValidator(new Reporter(pactVerifierConfig), pactVerifierConfig);
                validator.Validate(pactFile, ProviderStates);
            }
            finally
            {
                LogProvider.CurrentLogProvider.RemoveLogger(pactVerifierConfig.LoggerName);
            }
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ListLog.Expression != null)
            {
                targetCommand.AddParameter("ListLog", ListLog.Get(context));
            }

            if (LogName.Expression != null)
            {
                targetCommand.AddParameter("LogName", LogName.Get(context));
            }

            if (ListProvider.Expression != null)
            {
                targetCommand.AddParameter("ListProvider", ListProvider.Get(context));
            }

            if (ProviderName.Expression != null)
            {
                targetCommand.AddParameter("ProviderName", ProviderName.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (MaxEvents.Expression != null)
            {
                targetCommand.AddParameter("MaxEvents", MaxEvents.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (FilterXPath.Expression != null)
            {
                targetCommand.AddParameter("FilterXPath", FilterXPath.Get(context));
            }

            if (FilterXml.Expression != null)
            {
                targetCommand.AddParameter("FilterXml", FilterXml.Get(context));
            }

            if (FilterHashtable.Expression != null)
            {
                targetCommand.AddParameter("FilterHashtable", FilterHashtable.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (Oldest.Expression != null)
            {
                targetCommand.AddParameter("Oldest", Oldest.Get(context));
            }

            if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Exemplo n.º 20
0
        public override bool ProcessRecordAsync()
        {
            if (Stopping)
            {
                return(false);
            }

            var packageProvider = SelectProviders(ProviderName).ReEnumerable();

            if (ProviderName.IsNullOrEmpty())
            {
                Error(Constants.Errors.ProviderNameNotSpecified, packageProvider.Select(p => p.ProviderName).JoinWithComma());
                return(false);
            }

            switch (packageProvider.Count())
            {
            case 0:
                Error(Constants.Errors.UnknownProvider, ProviderName);
                return(false);

            case 1:
                break;

            default:
                Error(Constants.Errors.MatchesMultipleProviders, packageProvider.Select(p => p.ProviderName).JoinWithComma());
                return(false);
            }


            var provider = packageProvider.First();

            using (var sources = provider.ResolvePackageSources(this).CancelWhen(CancellationEvent.Token)) {
                // first, check if there is a source by this name already.
                var existingSources = sources.Where(each => each.IsRegistered && each.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToArray();

                if (existingSources.Any())
                {
                    // if there is, and the user has said -Force, then let's remove it.
                    foreach (var existingSource in existingSources)
                    {
                        if (Force)
                        {
                            if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, existingSource.Name, existingSource.Location, existingSource.ProviderName), Constants.Messages.ActionReplacePackageSource).Result)
                            {
                                var removedSources = provider.RemovePackageSource(existingSource.Name, this).CancelWhen(CancellationEvent.Token);
                                foreach (var removedSource in removedSources)
                                {
                                    Verbose(Constants.Messages.OverwritingPackageSource, removedSource.Name);
                                }
                            }
                        }
                        else
                        {
                            Error(Constants.Errors.PackageSourceExists, existingSource.Name);
                            return(false);
                        }
                    }
                }
            }

            string providerNameForProcessMessage = ProviderName.JoinWithComma();

            if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, Name, Location, providerNameForProcessMessage), FormatMessageString(Constants.Messages.ActionRegisterPackageSource)).Result)
            {
                //Need to resolve the path created via psdrive.
                //e.g., New-PSDrive -Name x -PSProvider FileSystem -Root \\foobar\myfolder. Here we are resolving x:\
                try
                {
                    if (FilesystemExtensions.LooksLikeAFilename(Location))
                    {
                        ProviderInfo providerInfo  = null;
                        var          resolvedPaths = GetResolvedProviderPathFromPSPath(Location, out providerInfo);

                        // Ensure the path is a single path from the file system provider
                        if ((providerInfo != null) && (resolvedPaths.Count == 1) && String.Equals(providerInfo.Name, "FileSystem", StringComparison.OrdinalIgnoreCase))
                        {
                            Location = resolvedPaths[0];
                        }
                    }
                } catch (Exception) {
                    //allow to continue handling the cases other than file system
                }

                using (var added = provider.AddPackageSource(Name, Location, Trusted, this).CancelWhen(CancellationEvent.Token)) {
                    foreach (var addedSource in added)
                    {
                        WriteObject(addedSource);
                    }
                }
                return(true);
            }

            return(false);
        }
Exemplo n.º 21
0
        /// <inheritdoc/>
        public string ToDelimitedString()
        {
            CultureInfo culture = CultureInfo.CurrentCulture;

            return(string.Format(
                       culture,
                       StringHelper.StringFormatSequence(0, 10, Configuration.FieldSeparator),
                       Id,
                       ProviderRole != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderRole.Select(x => x.ToDelimitedString())) : null,
                       ProviderName != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderName.Select(x => x.ToDelimitedString())) : null,
                       ProviderAddress != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderAddress.Select(x => x.ToDelimitedString())) : null,
                       ProviderLocation?.ToDelimitedString(),
                       ProviderCommunicationInformation != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderCommunicationInformation.Select(x => x.ToDelimitedString())) : null,
                       PreferredMethodOfContact?.ToDelimitedString(),
                       ProviderIdentifiers != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderIdentifiers.Select(x => x.ToDelimitedString())) : null,
                       EffectiveStartDateOfProviderRole.HasValue ? EffectiveStartDateOfProviderRole.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       EffectiveEndDateOfProviderRole.HasValue ? EffectiveEndDateOfProviderRole.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null
                       ).TrimEnd(Configuration.FieldSeparator.ToCharArray()));
        }
Exemplo n.º 22
0
 public BugTrackerWrapper(ProviderName providerName,string connString)
 {
     this.tracker = new BugTracer(providerName, connString);
 }
Exemplo n.º 23
0
        private IEnumerable <PackageProvider> FilterProvidersUsingDynamicParameters(MutableEnumerable <PackageProvider> providers, IEnumerable <PackageSource> userSpecifiedRegisteredSources, bool didUserSpecifyProviders, bool didUserSpecifySources)
        {
            var excluded = new Dictionary <string, IEnumerable <string> >(StringComparer.OrdinalIgnoreCase);

            var setparameters = DynamicParameterDictionary.Values.OfType <CustomRuntimeDefinedParameter>().Where(each => each.IsSet).ReEnumerable();

            var matchedProviders = (setparameters.Any() ? providers.Where(p => setparameters.All(each => each.Options.Any(opt => opt.ProviderName == p.ProviderName))) : providers).ReEnumerable();

            foreach (var provider in matchedProviders)
            {
                // if a 'required' parameter is not filled in, the provider should not be returned.
                // we'll collect these for warnings at the end of the filter.
                var missingRequiredParameters = DynamicParameterDictionary.Values.OfType <CustomRuntimeDefinedParameter>().Where(each => !each.IsSet && each.IsRequiredForProvider(provider.ProviderName)).ReEnumerable();
                if (!missingRequiredParameters.Any())
                {
                    yield return(provider);
                }
                else
                {
                    Collection <string> missingOptions = new Collection <string>();
                    foreach (var missingRequiredParameter in missingRequiredParameters)
                    {
                        foreach (var option in missingRequiredParameter.Options)
                        {
                            // remember these so we can warn later.
                            missingOptions.Add(option.Name);
                        }
                    }
                    excluded.Add(provider.ProviderName, missingOptions);
                }
            }

            /* TODO: provide errors in the case where everything got filtered out. Or maybe warnings?
             *
             * var mismatchedProviders = (setparameters.Any() ? providers.Where(each => !matchedProviders.Contains(each)).Where(p => setparameters.Any(each => each.Options.Any(opt => opt.ProviderName == p.ProviderName))) : Enumerable.Empty<PackageProvider>()).ReEnumerable();
             *
             * if (!found) {
             *  // we didn't find anything that matched
             *  // they specified dynamic parameters that implicitly select providers
             *  // that don't fit with the providers and sources that they initially asked for.
             *
             *  if (didUserSpecifyProviders || didUserSpecifySources) {
             *
             *      if (IsInvocation) {
             *          QueueHeldMessage(() => Error(Errors.ExcludedProvidersDueToMissingRequiredParameter, excluded.Keys, userSpecifiedSources.JoinWithComma()));
             *      }
             *
             *      yield break;
             *
             *  }
             *
             *  if (didUserSpecifySources) {
             *      // user gave sources which implied some providers but the dynamic parameters implied different providers
             *      if (IsInvocation) {
             *          // error
             *      }
             *      // return empty set
             *      return result;
             *  }
             *
             *  // well, this is silly.
             *  // if the user didn't specify a source or a provider
             *  // but the FilterProvidersUsingDynamicParameters came back empty
             *  // that means that they user specified parameters from two conflicting providers
             *  // and they forced each other out!
             *
             *  if (IsInvocation) {
             *      // error
             *
             *  }
             *
             * }
             */

            if (ProviderName != null && ProviderName.Any())
            {
                foreach (var providerName in ProviderName)
                {
                    if (excluded.ContainsKey(providerName))
                    {
                        Error(Constants.Errors.SpecifiedProviderMissingRequiredOption, providerName, excluded[providerName].JoinWithComma());
                    }
                }
            }

            // these warnings only show for providers that would have otherwise be selected.
            // if not for the missing requrired parameter.
            foreach (var mp in excluded.OrderBy(each => each.Key))
            {
                string optionsValue = mp.Value.JoinWithComma();

                if (userSpecifiedRegisteredSources.Any())
                {
                    var mp1 = mp;

                    //Check if the provider with missing dynamic parameters has been registered with the source provided by a user
                    var sources = userSpecifiedRegisteredSources.Where(source => source.ProviderName != null && source.ProviderName.EqualsIgnoreCase(mp1.Key));

                    if (didUserSpecifySources && sources.Any())
                    {
                        //Error out if the provider associated with the -source matches
                        Error(Constants.Errors.SpecifiedProviderMissingRequiredOption, mp.Key, optionsValue);
                    }
                }

                Verbose(Constants.Messages.SkippedProviderMissingRequiredOption, mp.Key, optionsValue);
            }
        }
Exemplo n.º 24
0
 /// <exclude />
 public override int GetHashCode()
 => DataId.GetHashCode() ^ InterfaceType.GetHashCode() ^ ProviderName.GetHashCode()
 ^ DataScopeIdentifier.GetHashCode() ^ LocaleScope.GetHashCode();
Exemplo n.º 25
0
        public override bool ProcessRecordAsync()
        {
            if (Stopping)
            {
                return(false);
            }

            var packageProvider = SelectProviders(ProviderName).ReEnumerable();

            if (ProviderName.IsNullOrEmpty())
            {
                Error(Constants.Errors.ProviderNameNotSpecified, packageProvider.Select(p => p.ProviderName).JoinWithComma());
                return(false);
            }

            switch (packageProvider.Count())
            {
            case 0:
                Error(Constants.Errors.UnknownProvider, ProviderName);
                return(false);

            case 1:
                break;

            default:
                Error(Constants.Errors.MatchesMultipleProviders, packageProvider.Select(p => p.ProviderName).JoinWithComma());
                return(false);
            }


            var provider = packageProvider.First();

            using (var sources = provider.ResolvePackageSources(this).CancelWhen(CancellationEvent.Token)) {
                // first, check if there is a source by this name already.
                var existingSources = sources.Where(each => each.IsRegistered && each.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToArray();

                if (existingSources.Any())
                {
                    // if there is, and the user has said -Force, then let's remove it.
                    foreach (var existingSource in existingSources)
                    {
                        if (Force)
                        {
                            if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, existingSource.Name, existingSource.Location, existingSource.ProviderName), Constants.Messages.ActionReplacePackageSource).Result)
                            {
                                var removedSources = provider.RemovePackageSource(existingSource.Name, this).CancelWhen(CancellationEvent.Token);
                                foreach (var removedSource in removedSources)
                                {
                                    Verbose(Constants.Messages.OverwritingPackageSource, removedSource.Name);
                                }
                            }
                        }
                        else
                        {
                            Error(Constants.Errors.PackageSourceExists, existingSource.Name);
                            return(false);
                        }
                    }
                }
            }

            string providerNameForProcessMessage = ProviderName.JoinWithComma();

            if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, Name, Location, providerNameForProcessMessage), FormatMessageString(Constants.Messages.ActionRegisterPackageSource)).Result)
            {
                using (var added = provider.AddPackageSource(Name, Location, Trusted, this).CancelWhen(CancellationEvent.Token)) {
                    foreach (var addedSource in added)
                    {
                        WriteObject(addedSource);
                    }
                }
                return(true);
            }

            return(false);
        }
        public virtual bool IsProviderEnabled()
        {
            bool   setting    = true;
            string settingStr = System.Configuration.ConfigurationManager.AppSettings["Enable-" + ProviderName.Replace(" ", "") + "Provider"];

            if (String.IsNullOrEmpty(settingStr))
            {
                return(setting);
            }
            bool.TryParse(settingStr, out setting);

            return(setting);
        }
Exemplo n.º 27
0
        public void Create_provider_without_error()
        {
            var provider = new Provider(ProviderName.Create("GeneDrinks").Value);

            provider.ShouldNotBeNull();
        }
Exemplo n.º 28
0
        protected IEnumerable <SoftwareIdentity> CheckMatchedDuplicates()
        {
            // if there are overmatched packages we need to know why:
            // are they found across multiple providers?
            // are they found across multiple sources?
            // are they all from the same source?

            foreach (var list in _resultsPerName.Values.Where(each => each != null && each.Any()))
            {
                if (list.Count == 1)
                {
                    //no overmatched
                    yield return(list.FirstOrDefault());
                }
                else
                {
                    //process the overmatched case
                    SoftwareIdentity selectedPackage = null;

                    var providers = list.Select(each => each.ProviderName).Distinct().ToArray();
                    var sources   = list.Select(each => each.Source).Distinct().ToArray();

                    //case: a user specifies -Source and multiple packages are found. In this case to determine which one should be installed,
                    //      We treat the user's package source array is in a priority order, i.e. the first package source has the highest priority.
                    //      Of course, these packages should not be from a single source with the same provider.
                    //      Example: install-package -Source @('src1', 'src2')
                    //               install-package -Source @('src1', 'src2') -Provider @('p1', 'p2')
                    if (Sources.Any() && (providers.Length != 1 || sources.Length != 1))
                    {
                        // let's use the first source as our priority.As long as we find a package, we exit the 'for' loop right away
                        foreach (var source in Sources)
                        {
                            //select all packages matched source
                            var pkgs = list.Where(package => source.EqualsIgnoreCase(package.Source) || (UserSpecifiedSourcesList.Keys.ContainsIgnoreCase(package.Source) && source.EqualsIgnoreCase(UserSpecifiedSourcesList[package.Source]))).ToArray();
                            if (pkgs.Length == 0)
                            {
                                continue;
                            }
                            if (pkgs.Length == 1)
                            {
                                //only one provider found the package
                                selectedPackage = pkgs[0];
                                break;
                            }
                            if (ProviderName == null)
                            {
                                //user does not specify '-providerName' but we found multiple packages with a source, can not determine which one
                                //will error out
                                break;
                            }
                            if (pkgs.Length > 1)
                            {
                                //case: multiple providers matched the same source.
                                //need to process provider's priority order
                                var pkg = ProviderName.Select(p => pkgs.FirstOrDefault(each => each.ProviderName.EqualsIgnoreCase(p))).FirstOrDefault();
                                if (pkg != null)
                                {
                                    selectedPackage = pkg;
                                    break;
                                }
                            }
                        }//inner foreach

                        //case: a user specifies -Provider array but no -Source and multiple packages are found. In this case to determine which one should be installed,
                        //      We treat the user's package provider array is in a priority order, i.e. the first provider in the array has the highest priority.
                        //      Of course, these packages should not be from a single source with the same provider.
                        //      Example: install-package -Provider @('p1', 'p2')
                    }
                    else if (ProviderName != null && ProviderName.Any() && (providers.Length != 1 || sources.Length != 1))
                    {
                        foreach (var providerName in ProviderName)
                        {
                            //select all packages matched with the provider name
                            var packages = list.Where(each => providerName.EqualsIgnoreCase(each.ProviderName)).ToArray();
                            if (packages.Length == 0)
                            {
                                continue;
                            }
                            if (packages.Length == 1)
                            {
                                //only one provider found the package, that's good
                                selectedPackage = packages[0];
                                break;
                            }
                            else
                            {
                                //user does not specify '-source' but we found multiple packages with one provider, we can not determine which one
                                //will error out
                                break;
                            }
                        }
                    }

                    if (selectedPackage != null)
                    {
                        yield return(selectedPackage);
                    }
                    else
                    {
                        //error out for the overmatched case
                        var suggestion = "";
                        if (providers.Length == 1)
                        {
                            // it's matching this package multiple times in the same provider.
                            if (sources.Length == 1)
                            {
                                // matching it from a single source.
                                // be more exact on matching name? or version?
                                suggestion = Resources.Messages.SuggestRequiredVersion;
                            }
                            else
                            {
                                // it's matching the same package from multiple sources
                                // tell them to use -source
                                suggestion = Resources.Messages.SuggestSingleSource;
                            }
                        }
                        else
                        {
                            // found across multiple providers
                            // must specify -provider
                            suggestion = Resources.Messages.SuggestSingleProviderName;
                        }

                        string searchKey = null;

                        foreach (var pkg in list)
                        {
                            Warning(Constants.Messages.MatchesMultiplePackages, pkg.SearchKey, pkg.ProviderName, pkg.Name, pkg.Version, GetPackageSourceNameOrLocation(pkg));
                            searchKey = pkg.SearchKey;
                        }
                        Error(Constants.Errors.DisambiguateForInstall, searchKey, GetMessageString(suggestion, suggestion));
                    }
                }
            }
        }
Exemplo n.º 29
0
        public string RecalculateConnectionString()
        {
            var rv = "";

            if (!String.IsNullOrEmpty(ProviderName))
            {
                switch (ProviderName.ToLower())
                {
                case "postgresql":
                    rv = String.Format(@"Server={0};Port={1};{2}User Id='{3}';Password='******';", ServerName, Port, (String.IsNullOrEmpty(DatabaseName) ? "" : "Database=" + DatabaseName + ";"), ("" + UserName).Replace("'", "''"), ("" + Password).Replace("'", "''"));
                    break;

                case "mysql":
                    rv = String.Format(@"Server={0};Port={1};{2}User ID={3};Password={4};Pooling=true;Connection Timeout=10;Protocol=socket;", ServerName, Port, (String.IsNullOrEmpty(DatabaseName) ? "" : "Database=" + DatabaseName + ";"), UserName, Password);
                    break;

                case "sqlite":
                    rv = String.Format(@"Data Source={0};Version=3';", DatabaseName);
                    break;

                case "sqlserver":

                    string initialCatalog = (String.IsNullOrEmpty(DatabaseName) ? "" : "Initial Catalog=" + DatabaseName + ";");

                    string separator = null;
                    if (String.IsNullOrEmpty(InstanceName))
                    {
                        // default instance, no separator
                        separator = "";
                    }
                    else
                    {
                        if (Toolkit.ToInt32(InstanceName, -1) > -1)
                        {
                            // using port, need a comma
                            separator = ", ";
                        }
                        else
                        {
                            // using instance name, need a backslash
                            separator = @"\";
                        }
                    }

                    if (UseWindowsAuthentication)
                    {
                        // assume integrated security -- either null user or specified SA and empty password.
                        //                dcs.ConnectionString = String.Format(@"Data Source={0}" + separator + @"{1};{2}Integrated Security=SSPI;", ServerName, instanceName, initialCatalog);
                        rv = String.Format(@"Data Source={0}" + separator + @"{1};{2}Trusted_Connection=True;", ServerName, InstanceName, initialCatalog);
                    }
                    else
                    {
                        rv = String.Format(@"Data Source={0}" + separator + @"{1};{2}User Id='{3}';Password='******';", ServerName, InstanceName, initialCatalog, ("" + UserName).Replace("'", "''"), ("" + Password).Replace("'", "''"));
                    }
                    break;

                case "oracle":
                    var dbPriv = "";
                    //if (("" + userName).ToUpper() == "SYS" || ("" + userName).ToUpper() == "SYSTEM") {
                    //    dbPriv = "DBA Privilege=SYSDBA;";
                    //}
                    //dcs.ConnectionString = String.Format(@"Data Source=XE;User Id='{2}';Password='******';{4}", ServerName, Port, ("" + userName).Replace("'", "''"), ("" + password).Replace("'", "''"), dbPriv);

                    var sid = String.IsNullOrEmpty(SID) ? "NO_SID_PROVIDED" : SID;

                    rv = String.Format(@"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={5})));User Id='{2}';Password='******';{4}", ServerName, Port, ("" + UserName).Replace("'", "''"), ("" + Password).Replace("'", "''"), dbPriv, sid);
                    break;

                default:
                    throw new NotImplementedException(getDisplayMember("ConnectionString{get}", "DataConnectionSpec does not define a connection string for providerName={0}", ProviderName));
                }
            }
            return(rv);
        }