public static InstanceInfo ResolveInstance(
            DbConnectionStringBuilder builder,
            bool isOdbc,
            QuerySource dbType
            )
        {
            InstanceInfo instance;

            if (dbType == QuerySource.SQLite || dbType == QuerySource.NetworkInformation)
            {
                instance = ResolveNonDatabase(
                    builder.ConnectionString,
                    dbType
                    );
            }
            else
            {
                instance = ResolveDatabase(
                    builder,
                    dbType,
                    isOdbc
                    );
            }

            return(instance);
        }
        private static AuthenticationInfo GetAuthentication(
            DbConnectionStringBuilder cnnBuilder,
            QuerySource sourceType
            )
        {
            switch (sourceType)
            {
            case QuerySource.MSSQL:
            case QuerySource.TDSQL:
                return(new AuthenticationInfo
                {
                    IsWindows = ReadBoolProp(cnnBuilder, "Integrated Security"),
                    Username = ReadProp(cnnBuilder, "uid", "User ID")  as string ?? string.Empty,
                    Password = ReadProp(cnnBuilder, "pwd", "Password") as string ?? string.Empty
                });

            default:
                return(new AuthenticationInfo
                {
                    IsWindows = true,
                    Username = string.Empty,
                    Password = string.Empty
                });
            }
        }
        private static InstanceInfo ResolveNonDatabase(
            string connection,
            QuerySource sourceType,
            bool isDynamicConnection = false
            )
        {
            InstanceInfo instanceInfo = new InstanceInfo(isDynamicConnection)
            {
                Instance  = connection,
                IsEnabled = true,
                IsODBC    = false,
                Name      = connection,

                Authentication = new AuthenticationInfo
                {
                    IsWindows = false,
                    Password  = string.Empty,
                    Username  = string.Empty
                },

                DbType = sourceType.ToString()
            };

            return(instanceInfo);
        }
        public void VBStringComparison()
        {
            var parameterExpression       = Expression.Parameter(typeof(Cook), "c");
            var vbCompareStringExpression =
                Expression.Equal(
                    Expression.Call(
                        typeof(Operators).GetMethod("CompareString"),
                        Expression.Constant("string1"),
                        Expression.MakeMemberAccess(parameterExpression, typeof(Cook).GetProperty("Name")),
                        Expression.Constant(true)),
                    Expression.Constant(0));
            var query = QuerySource
                        .Where(Expression.Lambda <Func <Cook, bool> > (vbCompareStringExpression, parameterExpression))
                        .Select(c => c.Name);

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            var whereClause = (WhereClause)queryModel.BodyClauses[0];

            var expectedExpression = new VBStringComparisonExpression(
                Expression.Equal(
                    Expression.Constant("string1"),
                    Expression.MakeMemberAccess(new QuerySourceReferenceExpression(queryModel.MainFromClause), typeof(Cook).GetProperty("Name"))),
                true);

            ExpressionTreeComparer.CheckAreEqualTrees(expectedExpression, whereClause.Predicate);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets CRUD schema from MySqlReader per particular QuerySource.
        /// If source is null then all columns from reader are copied.
        /// Note: this code was purposely made provider specific because other providers may treat some nuances differently
        /// </summary>
        public static Schema GetSchemaFromReader(string name, QuerySource source, MySqlDataReader reader)
        {
            var table = name;
            var fdefs = new List <Schema.FieldDef>();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                var fname = reader.GetName(i);
                var ftype = reader.GetFieldType(i);

                var def = new Schema.FieldDef(fname, ftype, source != null ? (source.HasPragma ? source.ColumnDefs[fname] : null) : null);
                fdefs.Add(def);
            }

            if (source != null)
            {
                if (source.HasPragma && source.ModifyTarget.IsNotNullOrWhiteSpace())
                {
                    table = source.ModifyTarget;
                }
            }

            if (table.IsNullOrWhiteSpace())
            {
                table = Guid.NewGuid().ToString();
            }

            return(new Schema(table, source != null ? source.ReadOnly : true, fdefs));
        }
        private static InstanceInfo ResolveDatabase(
            DbConnectionStringBuilder cnn,
            QuerySource sourceType,
            bool isOdbcConnection,
            bool isDynamicConnection = false
            )
        {
            AuthenticationInfo authentication = GetAuthentication(cnn, sourceType);

            log.InfoFormat("IsWindows:'{0}';Username:'******';Password:'******'",
                           authentication.IsWindows,
                           authentication.Username,
                           authentication.Password
                           );

            string instanceName = ReadProp(cnn, "Dsn", "Data Source") as string;

            InstanceInfo instance = new InstanceInfo(isDynamicConnection)
            {
                Authentication = authentication,
                Instance       = instanceName,
                IsEnabled      = true,
                Name           = instanceName,
                IsODBC         = isOdbcConnection,
                DbType         = sourceType.ToString()
            };

            if (isOdbcConnection)
            {
                instance.InnerOdbcConnectionString = cnn.ConnectionString;
            }

            return(instance);
        }
		private static InstanceInfo ResolveNonDatabase(
			string      connection,
			QuerySource sourceType,
			bool        isDynamicConnection = false
		)
		{
			InstanceInfo instanceInfo = new InstanceInfo(isDynamicConnection)
			{
				Instance  = connection,
				IsEnabled = true,
				IsODBC    = false,
				Name      = connection,

				Authentication = new AuthenticationInfo
				{
					IsWindows = false,
					Password  = string.Empty,
					Username  = string.Empty
				},

				DbType = sourceType.ToString()
			};

			return instanceInfo;
		}
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!ValidateConnections())
            {
                return;
            }

            if (this._updatesMade)
            {
                if (this._connectionGroup.Connections.Any())
                {
                    QuerySource dbType = this._connectionGroup.Connections.First().Type;

                    List <InstanceInfo> instances = this.lstConnectionStrings.Items
                                                    .OfType <InstanceInfo>().Where(i => i.Type == dbType).ToList();

                    this._connectionGroup.Connections = instances;

                    foreach (InstanceInfo instanceInfo in instances)
                    {
                        instanceInfo.ConnectionGroup = this._connectionGroup;
                    }

                    this._connectionsManager.UpdateGroupInstances(
                        this._connectionGroup, dbType.ToString()
                        );
                }

                DialogResult = DialogResult.OK;
            }
            else
            {
                DialogResult = DialogResult.Cancel;
            }
        }
		public override IQueryConnection CreateQueryConnection(
			QuerySource  sourceType,
			InstanceInfo instance
		)
		{
			IQueryConnection connection;

			lock (this._connectionPoolLock)
			{
				if (!this._connectionCache.ContainsKey(instance))
				{
					connection = base.CreateQueryConnection(sourceType, instance);

					this._connectionCache.Add(instance, connection);
				}

				connection = this._connectionCache[instance];
			}

			if (connection != null)
			{
				if (connection.State != ConnectionState.Closed)
				{
					connection.Close();
				}
			}

			return connection;
		}
Ejemplo n.º 10
0
        public void GroupJoin_WithoutSelect()
        {
            var query = QuerySource.GroupJoin(DetailQuerySource, s => s.ID, sd => sd.RoomNumber, (s, sds) => Tuple.Create(s, sds));

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            Assert.That(queryModel.GetOutputDataInfo().DataType, Is.SameAs(typeof(IQueryable <Tuple <Cook, IEnumerable <Kitchen> > >)));

            var mainFromClause = queryModel.MainFromClause;

            CheckConstantQuerySource(mainFromClause.FromExpression, QuerySource);
            Assert.That(mainFromClause.ItemType, Is.SameAs(typeof(Cook)));
            Assert.That(mainFromClause.ItemName, Is.EqualTo("s"));

            var groupJoinClause = ((GroupJoinClause)queryModel.BodyClauses[0]);

            Assert.That(groupJoinClause.ItemName, Is.SameAs("sds"));
            Assert.That(groupJoinClause.ItemType, Is.SameAs(typeof(IEnumerable <Kitchen>)));
            CheckConstantQuerySource(groupJoinClause.JoinClause.InnerSequence, DetailQuerySource);
            Assert.That(groupJoinClause.JoinClause.ItemType, Is.SameAs(typeof(Kitchen)));
            Assert.That(groupJoinClause.JoinClause.ItemName, Is.EqualTo("sd"));
            CheckResolvedExpression <Cook, int> (groupJoinClause.JoinClause.OuterKeySelector, mainFromClause, s => s.ID);
            CheckResolvedExpression <Kitchen, int> (groupJoinClause.JoinClause.InnerKeySelector, groupJoinClause.JoinClause, sd => sd.RoomNumber);

            var selectClause = queryModel.SelectClause;

            CheckResolvedExpression <Cook, IEnumerable <Kitchen>, Tuple <Cook, IEnumerable <Kitchen> > > (
                selectClause.Selector,
                mainFromClause,
                groupJoinClause,
                (s, sds) => Tuple.Create(s, sds));
        }
Ejemplo n.º 11
0
        public override IQueryConnection CreateQueryConnection(
            QuerySource sourceType,
            InstanceInfo instance
            )
        {
            IQueryConnection connection;

            lock (this._connectionPoolLock)
            {
                if (!this._connectionCache.ContainsKey(instance))
                {
                    connection = base.CreateQueryConnection(sourceType, instance);

                    this._connectionCache.Add(instance, connection);
                }

                connection = this._connectionCache[instance];
            }

            if (connection != null)
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
            }

            return(connection);
        }
Ejemplo n.º 12
0
        protected static DbConnectionStringBuilder GetConnectionStringBuilder(
            QuerySource source,
            string connectionString,
            bool isOdbc
            )
        {
            if (isOdbc)
            {
                return(new OdbcConnectionStringBuilder(connectionString));
            }

            DbConnectionStringBuilder builder;

            switch (source)
            {
            case QuerySource.MSSQL:
                builder = new SqlConnectionStringBuilder();
                break;

            case QuerySource.SQLite:
                // ODBC connection string builder is used
                // for SQLite internal connection
                // since it handles special connection string adequately
                builder = new OdbcConnectionStringBuilder();
                break;

            default:
                builder = new DbConnectionStringBuilder();
                break;
            }

            builder.ConnectionString = connectionString;

            return(builder);
        }
Ejemplo n.º 13
0
        private string Process(T state, StringBuilder builder, QuerySource query, string alias)
        {
            string name;

            if (query.TableName != null)
            {
                EscapeName(builder, query.TableName, true);
                name = alias ?? query.TableName;
            }
            else
            {
                builder.Append("(");
                var subName = Process(state, builder, query.TableQuery);
                builder.Append(")");
                alias = alias ?? subName;
                name  = alias;
            }

            if (!StencilUtils.IsNullOrWhiteSpace(alias))
            {
                builder.Append(" AS ");
                EscapeName(builder, alias, false);
            }
            return(name);
        }
Ejemplo n.º 14
0
        public void Join_WithoutSelect()
        {
            var query = QuerySource.Join(DetailQuerySource, s => s, sd => sd.Cook, (s, sd) => Tuple.Create(s, sd));

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            Assert.That(queryModel.GetOutputDataInfo().DataType, Is.SameAs(typeof(IQueryable <Tuple <Cook, Kitchen> >)));

            var mainFromClause = queryModel.MainFromClause;

            CheckConstantQuerySource(mainFromClause.FromExpression, QuerySource);
            Assert.That(mainFromClause.ItemType, Is.SameAs(typeof(Cook)));
            Assert.That(mainFromClause.ItemName, Is.EqualTo("s"));

            var joinClause = (JoinClause)queryModel.BodyClauses[0];

            CheckConstantQuerySource(joinClause.InnerSequence, DetailQuerySource);
            Assert.That(joinClause.ItemType, Is.SameAs(typeof(Kitchen)));
            Assert.That(joinClause.ItemName, Is.EqualTo("sd"));
            CheckResolvedExpression <Cook, Cook> (joinClause.OuterKeySelector, mainFromClause, s => s);
            CheckResolvedExpression <Kitchen, Cook> (joinClause.InnerKeySelector, joinClause, sd => sd.Cook);

            var selectClause = queryModel.SelectClause;

            CheckResolvedExpression <Cook, Kitchen, Tuple <Cook, Kitchen> > (
                selectClause.Selector,
                mainFromClause,
                joinClause,
                (s, sd) => Tuple.Create(s, sd));
        }
Ejemplo n.º 15
0
        public void DelegateAsSelector()
        {
            Func <Cook, string> expression = c => c.FirstName;
            var query = QuerySource.Select(c => c.Assistants.Select(expression));

            QueryParser.GetParsedQuery(query.Expression);
        }
Ejemplo n.º 16
0
        public void CovariantSubqueryTest()
        {
            IQueryable <object> subQueryable = (QuerySource.Select(c => c)).Distinct();
            var queryExpression = ExpressionHelper.MakeExpression(() => (
                                                                      from o in subQueryable
                                                                      select o));

            var queryModel = QueryParser.GetParsedQuery(queryExpression);

            Assert.That(queryModel.GetOutputDataInfo().DataType, Is.SameAs(typeof(IQueryable <object>)));

            var subQuery = ((SubQueryExpression)queryModel.MainFromClause.FromExpression).QueryModel;

            var selectOutputInfo = subQuery.SelectClause.GetOutputDataInfo();

            Assert.That(selectOutputInfo.ItemExpression.Type, Is.SameAs(typeof(Cook)));
            Assert.That(selectOutputInfo.ResultItemType, Is.SameAs(typeof(Cook)));
            Assert.That(selectOutputInfo.DataType, Is.SameAs(typeof(IQueryable <Cook>)));

            var distinctOperator           = (DistinctResultOperator)subQuery.ResultOperators.Single();
            var distinctOperatorOutputInfo = (StreamedSequenceInfo)distinctOperator.GetOutputDataInfo(selectOutputInfo);

            Assert.That(distinctOperatorOutputInfo.ItemExpression.Type, Is.SameAs(typeof(Cook)));
            Assert.That(distinctOperatorOutputInfo.ResultItemType, Is.SameAs(typeof(Cook)));
            Assert.That(distinctOperatorOutputInfo.DataType, Is.SameAs(typeof(IQueryable <Cook>)));

            var queryOutputInfo = (StreamedSequenceInfo)subQuery.GetOutputDataInfo();

            Assert.That(queryOutputInfo.ItemExpression.Type, Is.SameAs(typeof(Cook)));
            Assert.That(queryOutputInfo.ResultItemType, Is.SameAs(typeof(Cook)));
            Assert.That(queryOutputInfo.DataType, Is.SameAs(typeof(IQueryable <Cook>)));
        }
Ejemplo n.º 17
0
        private QuerySource GetCompanyNotices(int ID, int page)
        {
            const int   PageSize = 15;
            QuerySource model    = new QuerySource();
            var         query    = CompanyNoticeService.GetALL()
                                   .Where(x => x.MemberID == ID &&
                                          x.Status >= (int)CompanyNoticeStatus.ShowOnLine)
                                   .OrderByDescending(x => x.AddTime)
                                   .Skip((page - 1) * PageSize)
                                   .Take(PageSize)
                                   .ToList().Select(x => new LinkItem()
            {
                Name        = x.Title,
                Description = x.Content,
                ID          = x.ID,
                MemberID    = x.MemberID,
                AddTime     = x.AddTime
            }).ToList();
            int totalCount = CompanyNoticeService.GetALL()
                             .Count(x => x.MemberID == ID);

            model.Items       = query;
            model.CurrentPage = page;
            model.PageSize    = PageSize;
            model.TotalCount  = totalCount;
            return(model);
        }
		public static InstanceInfo ResolveInstance(
			DbConnectionStringBuilder builder,
			bool                      isOdbc,
			QuerySource               dbType
		)
		{
			InstanceInfo instance;

			if (dbType == QuerySource.SQLite || dbType == QuerySource.NetworkInformation)
			{
				instance = ResolveNonDatabase(
					builder.ConnectionString,
					dbType
				);
			}
			else
			{
				instance = ResolveDatabase(
					builder,
					dbType,
					isOdbc
				);
			}

			return instance;
		}
Ejemplo n.º 19
0
        public QuerySource GetCompanyCredentials(int ID, int page)
        {
            const int   PageSize = 15;
            QuerySource model    = new QuerySource();
            var         query    = CompanyCredentialsImgService.GetALL()
                                   .Where(x => x.MemberID == ID)
                                   .OrderByDescending(x => x.ID)
                                   .Skip((page - 1) * PageSize)
                                   .Take(PageSize)
                                   .ToList().Select(x => new LinkItem()
            {
                Name        = x.Title,
                ID          = x.ID,
                MemberID    = x.MemberID,
                FocusImgUrl = x.ImgUrl
            }).ToList();
            int totalCount = CompanyNoticeService.GetALL()
                             .Count(x => x.MemberID == ID);

            model.Items       = query;
            model.CurrentPage = page;
            model.PageSize    = PageSize;
            model.TotalCount  = totalCount;
            return(model);
        }
Ejemplo n.º 20
0
        public CountPerzons(MongoDBDataStore store) : base(store, null)
        {
            m_Source = new QuerySource(GetType().FullName,
                                       @"#pragma
modify=MyPerzon

{'Age': {'$gt': '$$fromAge', '$lt': '$$toAge'}}");
        }
Ejemplo n.º 21
0
        public void PRAGMA_2_nonModifiable()
        {
            var src =
                @"#pragma
key=counter,ssn
ignore=marker
load=counter
@last_name=lname
@first_name=fname
.last_name=This is description of last name

select
 1 as marker,
 t1.counter,
 t1.ssn,
 t1.lname as last_name,
 t1.fname as first_name,
 t1.c_doctor,
 t2.phone as doctor_phone,
 t2.NPI	as doctor_id
from
 tbl_patient t1
  left outer join tbl_doctor t2 on t1.c_doctor = t2.counter
where
 t1.lname like ?LN";

            var qs = new QuerySource("1", src);

            Assert.IsTrue(qs.HasPragma);
            Assert.IsTrue(qs.ReadOnly);
            Assert.AreEqual(string.Empty, qs.ModifyTarget);
            Assert.AreEqual(true, qs.ColumnDefs["counter"].Key);
            Assert.AreEqual(true, qs.ColumnDefs["ssn"].Key);
            Assert.AreEqual("lname", qs.ColumnDefs["last_name"].BackendName);
            Assert.AreEqual("fname", qs.ColumnDefs["first_name"].BackendName);
            Assert.AreEqual("This is description of last name", qs.ColumnDefs["last_name"].Description);
            Assert.AreEqual(StoreFlag.OnlyLoad, qs.ColumnDefs["counter"].StoreFlag);
            Assert.AreEqual(StoreFlag.None, qs.ColumnDefs["marker"].StoreFlag);

            Assert.AreEqual(StoreFlag.LoadAndStore, qs.ColumnDefs["ssn"].StoreFlag);

            Assert.AreEqual(
                @"select
 1 as marker,
 t1.counter,
 t1.ssn,
 t1.lname as last_name,
 t1.fname as first_name,
 t1.c_doctor,
 t2.phone as doctor_phone,
 t2.NPI	as doctor_id
from
 tbl_patient t1
  left outer join tbl_doctor t2 on t1.c_doctor = t2.counter
where
 t1.lname like ?LN
", qs.StatementSource);
        }
Ejemplo n.º 22
0
		public static InstanceInfo Create(string connection, QuerySource sourceType, bool isOdbcConnection)
		{
			if (IsDatabaseSource(sourceType))
			{
				return CreateDatabaseSelectConnection(connection, sourceType, isOdbcConnection);
			}

			return CreateNonDatabaseSelectConnection(connection, sourceType);
		}
Ejemplo n.º 23
0
        public void InvocationExpression_AppliedToInlineLambdaExpression()
        {
            var query = QuerySource.Where(c => ((Func <Cook, bool>)(c1 => c1.Name != null))(c)).Select(c => c.FirstName);

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            var predicate = ((WhereClause)queryModel.BodyClauses[0]).Predicate;

            CheckResolvedExpression <Cook, bool> (predicate, queryModel.MainFromClause, c => c.Name != null);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///     Returns a hash code for this object.
        /// </summary>
        /// <returns>
        ///     A hash code for this object.
        /// </returns>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = Alias?.GetHashCode() ?? 0;
                hashCode = (hashCode * 397) ^ (QuerySource?.GetHashCode() ?? 0);

                return(hashCode);
            }
        }
Ejemplo n.º 25
0
        public Connector.Query MakeQuery(Query query, QuerySource source)
        {
            var args = query.Select(p =>
            {
                var elm = Converter.ConvertCLRtoBSON(p.Name, p.Value, Store.TargetName);
                return(new TemplateArg(p.Name, elm.ElementType, elm.ObjectValue));
            }).ToArray();

            return(new Connector.Query(source.StatementSource, true, args));
        }
Ejemplo n.º 26
0
        public void Transformation_ViaAttributedInstanceMethod()
        {
            var query = QuerySource.Select(c => c.GetFullName());

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            var selectClause = queryModel.SelectClause;

            CheckResolvedExpression <Cook, string> (selectClause.Selector, queryModel.MainFromClause, c => c.FirstName + " " + c.Name);
        }
Ejemplo n.º 27
0
        public void Transformation_ViaAttributedInstanceProperty()
        {
            var query = QuerySource.Select(c => c.WeightInLbs);

            var queryModel = QueryParser.GetParsedQuery(query.Expression);

            var selectClause = queryModel.SelectClause;

            CheckResolvedExpression <Cook, double> (selectClause.Selector, queryModel.MainFromClause, c => c.Weight * 2.20462262);
        }
Ejemplo n.º 28
0
        public void WithoutPRAGMA_1()
        {
            var src = "abc";

            var qs = new QuerySource("1", src);

            Assert.IsFalse(qs.HasPragma);
            Assert.IsTrue(qs.ReadOnly);
            Assert.AreEqual("abc", qs.OriginalSource);
            Assert.AreEqual("abc", qs.StatementSource);
        }
Ejemplo n.º 29
0
        public Connector.Query MakeQuery(Connector.Database db, Query query, QuerySource source, out Connector.Collection collection)
        {
            if (source.ModifyTarget.IsNullOrWhiteSpace())
            {
                throw new MongoDbDataAccessException(StringConsts.QUERY_MODIFY_TARGET_MISSING_ERROR + "\n" + Source.OriginalSource);
            }

            collection = db[source.ModifyTarget];

            return(MakeQuery(query, source));
        }
Ejemplo n.º 30
0
        public void CovariantQueryTest()
        {
            IQueryable <object> queryable = QuerySource.Where(c => c.Name != "john");
            var queryExpression           = ExpressionHelper.MakeExpression(() => (queryable.Distinct()));

            var queryModel     = QueryParser.GetParsedQuery(queryExpression);
            var outputDataInfo = (StreamedSequenceInfo)queryModel.GetOutputDataInfo();

            Assert.That(outputDataInfo.DataType, Is.SameAs(typeof(IQueryable <object>)));
            Assert.That(outputDataInfo.ItemExpression.Type, Is.SameAs(typeof(Cook)));
        }
Ejemplo n.º 31
0
        private static string Translate(QuerySource source, string queryText, DateTime runTimestamp)
        {
            var db          = new PostgreeSqlDatabase(source.ConnectionString);
            var schemeStore = new PostgreeSqlSchemaStore(db);
            var translator  = new QueryToSqlTranslator(schemeStore, source.Areas)
            {
                CurrentDate = runTimestamp
            };

            return(translator.Translate(queryText));
        }
Ejemplo n.º 32
0
        private static IEnumerable <QueryInfo> GetQueries(LoaderRootWrapper wrapper, QuerySource querySource)
        {
            List <QueryInfo> queryInfos = wrapper.GetQueriesOfType(querySource).SelectMany(w => w.Infos).ToList();

            queryInfos.ForEach(q =>
            {
                q.OnDesialized();
                q.Source = querySource;
            });

            return(queryInfos);
        }
        private static bool IsDatabaseSource(QuerySource sourceType)
        {
            switch (sourceType)
            {
            case QuerySource.MSSQL:
            case QuerySource.SQLite:
            case QuerySource.TDSQL:
                return(true);
            }

            return(false);
        }
Ejemplo n.º 34
0
		private static bool IsDatabaseSource(QuerySource sourceType)
		{
			switch (sourceType)
			{
				case QuerySource.MSSQL:
				case QuerySource.SQLite:
				case QuerySource.TDSQL:
					return true;
			}

			return false;
		}
		public static IConnectionStringDialog CreateDialog(QuerySource querySource, MsSqlAuditorModel model)
		{
			switch (querySource)
			{
				case QuerySource.MSSQL:
					return new CommonConnectionStringDialog();
				case QuerySource.SQLite:
					return new InternalSqliteConnectionDialog(model);
				case QuerySource.NetworkInformation:
					return new NetworkInformationConnectionDialog();
				default:
					return new NonSqlDataConnectionDialog();
			}
		}
		public static List<InstanceInfo> ResolveInstances(
			List<Tuple<DbConnectionStringBuilder, bool>> connectionProperties,
			QuerySource                                  dbType
		)
		{
			List<InstanceInfo> instances = new List<InstanceInfo>();

			foreach (Tuple<DbConnectionStringBuilder, bool> properties in connectionProperties)
			{
				DbConnectionStringBuilder cnn = properties.Item1;
				bool isOdbc                   = properties.Item2;
				InstanceInfo instance         = ResolveInstance(cnn, isOdbc, dbType);

				instances.Add(instance);
			}

			return instances;
		}
Ejemplo n.º 37
0
		private static InstanceInfo CreateNonDatabaseSelectConnection(string connection, QuerySource sourceType)
		{
			var instanceInfo = new InstanceInfo(true)
			{
				Instance       = connection,
				IsEnabled      = true,
				IsODBC         = false,
				Name           = connection,
				Authentication = new AuthenticationInfo
				{
					IsWindows = false,
					Password  = string.Empty,
					Username  = string.Empty
				},
				DbType         = sourceType.ToString()
			};

			return instanceInfo;
		}
		/// <summary>
		/// The create trial connection group.
		/// </summary>
		/// <param name="propertiesList">The properties list.</param>
		/// <param name="templateFile">Path to temlate file</param>
		/// <param name="dbType">Type DB</param>
		/// <param name="connectionGroupName">Name connection group</param>
		/// <param name="isExternalTemplate">Is opened from user file template </param>
		/// <returns>
		/// The <see cref="ConnectionGroupInfo" />.
		/// </returns>
		public static ConnectionGroupInfo CreateTrialConnectionGroup(
			List<Tuple<DbConnectionStringBuilder, bool>> propertiesList,
			string                                       templateFile,
			QuerySource                                  dbType,
			string                                       connectionGroupName,
			bool                                         isExternalTemplate
		)
		{
			ConnectionGroupInfo connectionGroup = new ConnectionGroupInfo
			{
				Connections      = InstanceInfoResolver.ResolveInstances(propertiesList, dbType),
				IsExternal       = isExternalTemplate,
				TemplateDir      = Path.GetDirectoryName(templateFile),
				TemplateFileName = Path.GetFileName(templateFile),
				Name             = connectionGroupName
			};

			return connectionGroup;
		}
		public static InstanceInfo ResolveDynamicInstance(
			string      connection,
			QuerySource sourceType,
			bool        isOdbcConnection
		)
		{
			if (IsDatabaseSource(sourceType))
			{
				return ResolveDatabase(
					connection,
					sourceType,
					isOdbcConnection,
					true
				);
			}

			return ResolveNonDatabase(
				connection,
				sourceType,
				true
			);
		}
		public IQueryConnection CreateQueryConnection(QuerySource sourceType, InstanceInfo instance)
		{
			bool        isOdbc    = instance.IsODBC;
			QuerySource queryType = instance.Type;

			instance.SetSettings(this._model.Settings);

			if (sourceType == QuerySource.SQLite)
			{
				IStorageManager storageManager = this._model.GetVaultProcessor(
					instance.ConnectionGroup ?? new ConnectionGroupInfo()
				);

				AttachingSqliteQueryConnection sqliteQueryConnection;
				string                         connectionString = instance.GetConnectionString();
				SqliteConnectionParameters     connectionParameters = SqliteConnectionParameters.Parse(connectionString);

				if (connectionParameters.IsValid)
				{
					sqliteQueryConnection = new SqliteInnerQueryConnection(
						storageManager.CurrentStorage,
						connectionParameters
					);
				}
				else
				{
					sqliteQueryConnection = new SqliteInternalQueryConnection(
						storageManager.CurrentStorage,
						instance
					);
				}

				if (storageManager.HistoryStorage != null)
				{
					foreach (var historyStorage in storageManager.HistoryStorage)
					{
						sqliteQueryConnection.AddDatabaseToAttach(
							historyStorage.Alias,
							historyStorage.FileName
						);
					}
				}

				if (storageManager.ReportStorage != null)
				{
					sqliteQueryConnection.AddDatabaseToAttach(
						"report",
						storageManager.ReportStorage.FileName
					);
				}

				return sqliteQueryConnection;
			}

			if (isOdbc)
			{
				OdbcConnection odbcConnection = ConnectionFactory.CreateOdbcConnection(instance, true);

				return new OdbcQueryConnection(odbcConnection);
			}

			if (sourceType == queryType)
			{
				switch (sourceType)
				{
					case QuerySource.MSSQL:
						SqlConnection sqlConnection =
							ConnectionFactory.CreateSqlConnection(instance, true);

						return new MsSqlQueryConnection(sqlConnection);

					case QuerySource.TDSQL:
						TdConnection tdConnection =
							ConnectionFactory.CreateTdConnection(instance, true);

						return new TeradataSqlQueryConnection(tdConnection);

					case QuerySource.SQLiteExternal:
						SQLiteConnection sqliteConnection =
							ConnectionFactory.CreateSQLiteExternalConnection(instance);

						return new SqliteExternalQueryConnection(sqliteConnection);

					case QuerySource.ActiveDirectory:
						ActiveDirectoryConnection activeDirectoryConnection =
							ConnectionFactory.CreateActiveDirectoryConnection(instance);

						return new ActiveDirectoryQueryConnection(activeDirectoryConnection);

					case QuerySource.EventLog:
						EventLogConnection eventLogConnection =
							ConnectionFactory.CreateEventLogConnection(instance);

						return new EventLogQueryConnection(eventLogConnection);

					case QuerySource.NetworkInformation:
						NetworkInformationConnection networkInfoConnection =
							ConnectionFactory.CreateNetworkInformationConnection(instance);

						return new NetworkInformationQueryConnection(networkInfoConnection);
				}
			}

			string errorMessage = String.Format(
				"There is no QueryConnection defined. QuerySource: {0}, QueryType: {1}",
				sourceType,
				queryType
			);

			Log.ErrorFormat(errorMessage);

			throw new ArgumentException(errorMessage);
		}
		private static InstanceInfo ResolveDatabase(
			string      connection,
			QuerySource sourceType,
			bool        isOdbcConnection,
			bool        isDynamicConnection = false
		)
		{
			DbConnectionStringBuilder connectionBuilder = new DbConnectionStringBuilder
			{
				ConnectionString = connection
			};

			return ResolveDatabase(
				connectionBuilder,
				sourceType,
				isOdbcConnection,
				isDynamicConnection
			);
		}
		private static InstanceInfo ResolveDatabase(
			DbConnectionStringBuilder cnn,
			QuerySource               sourceType,
			bool                      isOdbcConnection,
			bool                      isDynamicConnection = false
		)
		{
			AuthenticationInfo authentication = GetAuthentication(cnn, sourceType);

			log.InfoFormat("IsWindows:'{0}';Username:'******';Password:'******'",
				authentication.IsWindows,
				authentication.Username,
				authentication.Password
			);

			string instanceName = ReadProp(cnn, "Dsn", "Data Source") as string;

			InstanceInfo instance = new InstanceInfo(isDynamicConnection)
			{
				Authentication = authentication,
				Instance       = instanceName,
				IsEnabled      = true,
				Name           = instanceName,
				IsODBC         = isOdbcConnection,
				DbType         = sourceType.ToString()
			};

			if (isOdbcConnection)
			{
				instance.InnerOdbcConnectionString = cnn.ConnectionString;
			}

			return instance;
		}
		protected static DbConnectionStringBuilder GetConnectionStringBuilder(
			QuerySource source,
			string      connectionString,
			bool        isOdbc
		)
		{
			if (isOdbc)
			{
				return new OdbcConnectionStringBuilder(connectionString);
			}

			DbConnectionStringBuilder builder;

			switch (source)
			{
				case QuerySource.MSSQL:
					builder = new SqlConnectionStringBuilder();
					break;

				case QuerySource.SQLite:
					// ODBC connection string builder is used
					// for SQLite internal connection
					// since it handles special connection string adequately
					builder = new OdbcConnectionStringBuilder();
					break;

				default:
					builder = new DbConnectionStringBuilder();
					break;
			}

			builder.ConnectionString = connectionString;

			return builder;
		}
Ejemplo n.º 44
0
		ISqlPredicate MakeIsPredicate(IParseContext context, QuerySource.Table table, Type typeOperand)
		{
			if (typeOperand == table.ObjectType && table.InheritanceMapping.Count(m => m.Type == typeOperand) == 0)
				return Convert(context, new SqlQuery.Predicate.Expr(new SqlValue(true)));

			var mapping = table.InheritanceMapping.Select((m,i) => new { m, i }).Where(m => m.m.Type == typeOperand && !m.m.IsDefault).ToList();

			switch (mapping.Count)
			{
				case 0:
					{
						var cond = new SqlQuery.SearchCondition();

						foreach (var m in table.InheritanceMapping.Select((m,i) => new { m, i }).Where(m => !m.m.IsDefault))
						{
							cond.Conditions.Add(
								new SqlQuery.Condition(
									false, 
									Convert(context,
										new SqlQuery.Predicate.ExprExpr(
											table.Columns[table.InheritanceDiscriminators[m.i]].Field,
											SqlQuery.Predicate.Operator.NotEqual,
											new SqlValue(m.m.Code)))));
						}

						return cond;
					}

				case 1:
					return Convert(context,
						new SqlQuery.Predicate.ExprExpr(
							table.Columns[table.InheritanceDiscriminators[mapping[0].i]].Field,
							SqlQuery.Predicate.Operator.Equal,
							new SqlValue(mapping[0].m.Code)));

				default:
					{
						var cond = new SqlQuery.SearchCondition();

						foreach (var m in mapping)
						{
							cond.Conditions.Add(
								new SqlQuery.Condition(
									false,
									Convert(context,
										new SqlQuery.Predicate.ExprExpr(
											table.Columns[table.InheritanceDiscriminators[m.i]].Field,
											SqlQuery.Predicate.Operator.Equal,
											new SqlValue(m.m.Code))),
									true));
						}

						return cond;
					}
			}
		}
Ejemplo n.º 45
0
		private static LoaderMSSQLQueryWrapper ReadLoaderQueryWrapper(List<QueryInfo> queries, QuerySource querySource)
		{
			LoaderMSSQLQueryWrapper queryWrapper = new LoaderMSSQLQueryWrapper
			{
				Infos = queries.Where(query => query.Source == querySource).ToList(),
				Type  = querySource.ToString()
			};

			return queryWrapper;
		}
		/// <summary>
		/// Check template database type.
		/// </summary>
		/// <param name="model">Model mssql auditor.</param>
		/// <param name="template">Template.</param>
		/// <param name="selectedSource">Selected db source.</param>
		/// <returns>If template available.</returns>
		public static bool CheckFromXml(MsSqlAuditorModel model, Template template, QuerySource selectedSource)
		{
			return template.DBType == selectedSource;
		}
Ejemplo n.º 47
0
		[Conditional("TRACE_PARSING")] public static void WriteLine(string prefix, QuerySource   source) { WriteLineInternal(prefix,   source); }
		public virtual IQueryConnection CreateQueryConnection(QuerySource sourceType, InstanceInfo instance)
		{
			return this._connectionFactory.CreateQueryConnection(sourceType, instance);
		}
		private static AuthenticationInfo GetAuthentication(
			DbConnectionStringBuilder cnnBuilder,
			QuerySource               sourceType
		)
		{
			switch (sourceType)
			{
				case QuerySource.MSSQL:
				case QuerySource.TDSQL:
					return new AuthenticationInfo
					{
						IsWindows = ReadBoolProp(cnnBuilder, "Integrated Security"),
						Username  = ReadProp(cnnBuilder, "uid", "User ID")  as string ?? string.Empty,
						Password  = ReadProp(cnnBuilder, "pwd", "Password") as string ?? string.Empty
					};

				default:
					return new AuthenticationInfo
					{
						IsWindows = true,
						Username = string.Empty,
						Password = string.Empty
					};
			}
		}
Ejemplo n.º 50
0
		public BindingWrapper<ConnectionType> GetConnectionType(QuerySource dbType)
		{
			ConnectionType[] connectionTypes = Settings.SystemSettings.ConnectionTypes;

			if (connectionTypes != null)
			{
				foreach (ConnectionType connectionType in connectionTypes)
				{
					QuerySource querySource;

					if (Enum.TryParse(connectionType.Id, true, out querySource))
					{
						if (querySource == dbType)
						{
							return new BindingWrapper<ConnectionType>(
								connectionType,
								ct =>
								{
									i18n localeItem = ct.Locales.FirstOrDefault(
										l => l.Language == Settings.InterfaceLanguage
									);

									string displayName = localeItem != null
										? localeItem.Text
										: ct.Id;

									return displayName.RemoveWhitespaces();
								}
							);
						}
					}
				}
			}

			return null;
		}
Ejemplo n.º 51
0
 		private static IEnumerable<QueryInfo> GetQueries(LoaderRootWrapper wrapper, QuerySource querySource)
 		{
			List<QueryInfo> queryInfos = wrapper.GetQueriesOfType(querySource).SelectMany(w => w.Infos).ToList();

			queryInfos.ForEach(q =>
			{
				q.OnDesialized();
				q.Source = querySource;
			});

			return queryInfos;
		}
Ejemplo n.º 52
0
		private static InstanceInfo CreateDatabaseSelectConnection(string connection, QuerySource sourceType, bool isOdbcConnection)
		{
			bool   AuthenticationInfoIsWindows = false;
			string AuthenticationInfoUsername  = string.Empty;
			string AuthenticationInfoPassword  = string.Empty;

			var connectionDialog = new DataConnectionDialog();

			connectionDialog.DataSources.Add(DataSource.OdbcDataSource);
			connectionDialog.DataSources.Add(DataSource.SqlDataSource);
			connectionDialog.SelectedDataSource = isOdbcConnection ? DataSource.OdbcDataSource : DataSource.SqlDataSource;
			connectionDialog.UnspecifiedDataSource.Providers.Add(DataProvider.SqlDataProvider);
			connectionDialog.ConnectionString = connection;

			var properties = connectionDialog.ConnectionProperties;

			if (sourceType == QuerySource.MSSQL)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.TDSQL)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.SQLite)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.SQLiteExternal)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.ActiveDirectory)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.EventLog)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else if (sourceType == QuerySource.NetworkInformation)
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}
			else
			{
				AuthenticationInfoIsWindows = true;
				AuthenticationInfoUsername  = string.Empty;
				AuthenticationInfoPassword  = string.Empty;
			}

			if (properties["Integrated Security"] != null)
			{
				if (properties["Integrated Security"] as bool)
				{
					AuthenticationInfoIsWindows = true;
				}
				else
				{
					AuthenticationInfoIsWindows = false;
				}
			}

			if (properties["uid"] != null)
			{
				if (!string.IsNullOrEmpty(properties["uid"] as string))
				{
					AuthenticationInfoIsWindows = false;
					AuthenticationInfoUsername  = properties["uid"] as string;
				}
			}

			if (properties["User ID"] != null)
			{
				if (!string.IsNullOrEmpty(properties["User ID"] as string))
				{
					AuthenticationInfoIsWindows = false;
					AuthenticationInfoUsername  = properties["User ID"] as string;
				}
			}

			if (properties["pwd"] != null)
			{
				if (!string.IsNullOrEmpty(properties["pwd"] as string))
				{
					AuthenticationInfoIsWindows = false;
					AuthenticationInfoPassword  = properties["pwd"] as string;
				}
			}

			if (properties["Password"] != null)
			{
				if (!string.IsNullOrEmpty(properties["Password"] as string))
				{
					AuthenticationInfoIsWindows = false;
					AuthenticationInfoPassword  = properties["Password"] as string;
				}
			}

			log.InforFormat("IsWindows:'{0}';Username:'******';Password:'******',
				AuthenticationInfoIsWindows
				AuthenticationInfoUsername,
				AuthenticationInfoPassword,
			);

			var instance = new InstanceInfo(true)
			{
				Authentication = new AuthenticationInfo
					{
						// IsWindows = properties["Integrated Security"] as bool?   ?? false,
						// Username = (properties["uid"]                 as string) ?? (properties["User ID"]  as string) ?? string.Empty,
						// Password = (properties["pwd"]                 as string) ?? (properties["Password"] as string) ?? string.Empty
						IsWindows = AuthenticationInfoIsWindows,
						Username  = AuthenticationInfoUsername,
						Password  = AuthenticationInfoPassword
					},
				Instance  = (properties["Dsn"] as string) ?? (properties["Data Source"] as string),
				IsEnabled = true,
				Name      = (properties["Dsn"] as string) ?? (properties["Data Source"] as string),
				IsODBC    = isOdbcConnection,
				DbType    = sourceType.ToString()
			};

			if (instance.IsODBC)
			{
				instance.SetInnerODBCCOnnectionString(connection);
			}

			return instance;
		}
Ejemplo n.º 53
0
			public List<LoaderMSSQLQueryWrapper> GetQueriesOfType(QuerySource querySource)
			{
				return _sqlInfos.Where(x => x.DBType == querySource).ToList();
			}