コード例 #1
0
        private void UpdateDynamicChildren(CancellationToken cancellationToken)
        {
            ChildrenAreLoadingNow = true;

            try
            {
                List <TemplateNodeInfo> newNodes = new List <TemplateNodeInfo>();

                using (SqlProcessor sqlProcessor = this._model.GetNewSqlProcessor(cancellationToken))
                {
                    foreach (TemplateNodeQueryInfo query in GroupQueries)
                    {
                        List <TemplateNodeInfo> templateNodesToBeReplicated = GetSubnodesFor(query).ToList();
                        List <QueryInfo>        queryInfos = this._model.GetQueryByTemplateNodeQueryInfo(query);

                        foreach (InstanceInfo serverInstance in Connection.ConnectionGroup.Connections.Where(c => c.IsEnabled))
                        {
                            cancellationToken.ThrowIfCancellationRequested();

                            QueryInfo queryInfo = queryInfos.FirstOrDefault(x =>
                                                                            x.Source == serverInstance.Type || x.Source == QuerySource.SQLite
                                                                            );

                            DataTable[] tables = GetGroupSelectResultsFromServer(sqlProcessor, serverInstance, queryInfo, query);

                            cancellationToken.ThrowIfCancellationRequested();

                            foreach (DataTable t in tables)
                            {
                                for (int rowIndex = 0; rowIndex < t.Rows.Count; rowIndex++)
                                {
                                    List <TemplateNodeInfo> replicants =
                                        templateNodesToBeReplicated.Select(
                                            tn => tn.Instantiate(
                                                Connection,
                                                t.Rows[rowIndex],
                                                query,
                                                this
                                                )
                                            ).ToList();
                                    newNodes.AddRange(replicants);
                                }
                            }
                        }
                    }
                }

                cancellationToken.ThrowIfCancellationRequested();

                if (newNodes.Count == 0)
                {
                    return;
                }

                lock (Childs)
                {
                    Childs.AddRange(newNodes);

                    this._model.GetVaultProcessor(Connection.ConnectionGroup).CurrentStorage.NodeInstances.SaveChildren(this);
                }
            }
            catch (Exception ex)
            {
                log.Error("private Task CreateAddDynamicChildrenTask(Action done)", ex);
            }
            finally
            {
                ChildrenAreLoadingNow = false;
            }
        }
コード例 #2
0
		/// <summary>
		/// The sign query item.
		/// </summary>
		/// <param name="cryptoProcessor">The crypto processor.</param>
		/// <param name="itemInfo">The item info.</param>
		/// <param name="query">The query.</param>
		private void SignQueryItem(CryptoProcessor cryptoProcessor, QueryItemInfo itemInfo, QueryInfo query)
		{
			this._logger.WriteToLog("prepare to sign the query....");

			itemInfo.ParentQuery = query;
			new QueryPreparator(this.Settings, this._logger).PrepareIfNeeds(itemInfo);

			this._logger.WriteToLog("Sign query....");

			itemInfo.Signature = cryptoProcessor.Sign(itemInfo.Text);
		}
コード例 #3
0
        /// <summary>
        /// Load queries with signature check
        /// </summary>
        /// <param name="filename">Xml-file name</param>
        /// <param name="isExternal">Is opened from user file template</param>
        /// <returns>Queries list</returns>
        public List <QueryInfo> LoadQueries(string filename, bool isExternal)
        {
            log.InfoFormat("filename:'{0}',isExternal:'{1}'",
                           filename ?? "<null>",
                           isExternal
                           );

            List <string>   wrongQueries    = new List <string>();
            CryptoProcessor cryptoProcessor = null;

            try
            {
                if (AppVersionHelper.IsNotDebug())
                {
                    cryptoProcessor = new CryptoProcessor(
                        Settings.SystemSettings.PublicKeyXmlSign,
                        Settings.SystemSettings.PrivateKeyXmlDecrypt
                        );
                }
            }
            catch (System.Security.XmlSyntaxException ex)
            {
                log.Error(ex);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                log.Error(ex.GetBaseException());
            }

            List <QueryInfo> queries = QueriesLoader.LoadFromXml(filename, cryptoProcessor, isExternal);

            for (int i = queries.Count - 1; i >= 0; i--)
            {
                QueryInfo query = queries[i];

                log.InfoFormat("query:'{0}'", query);

                if (AppVersionHelper.IsNotDebug() && !isExternal)
                {
                    for (int j = query.DatabaseSelect.Count - 1; j >= 0; j--)
                    {
                        QueryItemInfo queryItem = query.DatabaseSelect[j];

                        if (cryptoProcessor != null && !cryptoProcessor.Verify(queryItem.Text, queryItem.Signature))
                        {
                            if (!wrongQueries.Contains(query.Name))
                            {
                                wrongQueries.Add(query.Name);
                            }

                            query.DatabaseSelect.RemoveAt(j);
                        }
                    }

                    for (int j = query.Items.Count - 1; j >= 0; j--)
                    {
                        QueryItemInfo queryItem = query.Items[j];

                        log.InfoFormat("queryItem.Text:'{0}'", queryItem.Text);

                        if (cryptoProcessor != null && !cryptoProcessor.Verify(queryItem.Text, queryItem.Signature))
                        {
                            if (!wrongQueries.Contains(query.Name))
                            {
                                wrongQueries.Add(query.Name);
                            }

                            query.Items.RemoveAt(j);
                        }
                    }
                }

                if (query.Items.Count == 0)
                {
                    queries.RemoveAt(i);
                }
            }

            if ((Settings.WarnAboutUnsignedQuery) && (wrongQueries.Count > 0))
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(filename + Environment.NewLine + Environment.NewLine);

                foreach (string wrongQuery in wrongQueries)
                {
                    sb.Append(wrongQuery + Environment.NewLine);
                }

                MessageBox.Show(sb.ToString(), LocaleManager.GetLocalizedText(LocaleManager.Exceptions, "wrongQueriesSignatures"));
            }

            return(queries);
        }
コード例 #4
0
		private void SaveHistoryData(
			QueryInfo             query,
			InstanceInfo          instance,
			long                  queryId,
			TemplateNodeQueryInfo templateNodeQuery
		)
		{
			QueryInfo queryInfo            = new QueryInfo { Source = QuerySource.SQLite };
			Regex     regex                = new Regex(@"\[\$\{(?<QueryName>[\w]+)\}\$_\$\{(?<RecordSetNumber>[\w]+)\}\$\]");
			string    strQueryName         = String.Empty;
			Int64     intRecordSetNumber   = 0L;
			string    strReplacedTableName = String.Empty;

			if (query.FillStatementList == null)
			{
				return;
			}

			List<HistoryFillStatement> list = query.FillStatementList.GetSortedStatements();

			List<QueryParameterInfo> parameters = new List<QueryParameterInfo>
			{
				new QueryParameterInfo
				{
					Name = _QueryIdParameterName,
					Type = SqlDbType.BigInt
				}
			};

			List<ParameterValue> paramterValues = new List<ParameterValue>
			{
				new ParameterValue
				{
					Name        = _QueryIdParameterName,
					StringValue = queryId.ToString()
				}
			};

			// string newTableName = String.Format("[{0}]",
			//    this.GetTableName(templateNodeQuery, recordSet) ?? "_unknown_table_"
			// );

			// string oldTableName = "[${" + query.Name + "}$_${" + recordSet + "}$]";

			// string oldTableName = String.Format("[${{{0}}}$_${{{1}}}$]",
			//   query.Name ?? "_unknown_table_",
			//   recordSet
			//);

			// Log.DebugFormat("oldTableName:'{0}',newTableName:'{1}'",
			//    oldTableName,
			//    newTableName
			//);

			foreach (HistoryFillStatement statement in list)
			{
				QueryItemInfo queryItem = new QueryItemInfo();

				queryItem.ParentQuery = queryInfo;
				queryItem.Text        = statement.Text;

				// queryItem.Text        = statement.Text.Replace(oldTableName, newTableName);

				// Regex regex = new Regex("[\$\{([\w]+)\}\$_\$\{([\w]+)\}\$]");

				// Log.InfoFormat("regex:'{0}'",
				//    regex
				// );

				var results = regex.Matches(statement.Text);

				foreach (Match match in results)
				{
					// Log.InfoFormat("match:'{0}';match.Value:'{1}'",
					// 	match,
					// 	match.Value
					// );

					strQueryName       = match.Groups["QueryName"].Value;
					intRecordSetNumber = Int64.Parse(match.Groups["RecordSetNumber"].Value);

					// Log.InfoFormat("strQueryName:'{0}';intRecordSetNumber:'{1}'",
					//    strQueryName,
					//    intRecordSetNumber
					// );

					if (String.Equals(strQueryName, query.Name, StringComparison.OrdinalIgnoreCase))
					{
						// Log.InfoFormat("matches:strQueryName:'{0}';query.Name:'{1}'",
						//    strQueryName,
						//    query.Name
						// );

						strReplacedTableName = string.Format(
							"[{0}]",
							this.GetTableName(
								templateNodeQuery,
								intRecordSetNumber
							)
						);

						// Log.InfoFormat("strReplacedTableName:'{0}'",
						//    strReplacedTableName
						// );

						// Log.InfoFormat("queryItem.Text:'{0}'",
						//    queryItem.Text
						// );

						queryItem.Text = queryItem.Text.Replace(
							match.Value,
							strReplacedTableName
						);

						// Log.InfoFormat("queryItem.Text:'{0}'",
						//    queryItem.Text
						// );
					}
				}

				this.ExecuteSql(
					instance,
					queryItem,
					parameters,
					paramterValues
				);
			}
		}
コード例 #5
0
		internal DataTable[] ExecuteSql(
			InstanceInfo                    instance,
			QueryInfo                       query,
			string                          database = null,
			IEnumerable<QueryParameterInfo> parameters = null,
			IEnumerable<ParameterValue>     parameterValues = null,
			ProgressItem                    progress = null,
			bool                            fromGroupSelect = false
		)
		{
			InstanceVersion ver           = instance.ServerProperties.Version;
			QueryItemInfo exactSqlVersion = query.Items.GetQueryItemForVersion(ver);

			if (exactSqlVersion == null)
			{
				throw new InvalidOperationException("No <sql-select-text> found for version " + ver + " in <sql-select name=" + query.Name);
			}

			return ExecuteSql(
				instance,
				exactSqlVersion,
				database,
				parameters,
				parameterValues,
				progress,
				fromGroupSelect
			);
		}
コード例 #6
0
		/// <summary>
		/// The execute query.
		/// </summary>
		/// <param name="instance">The instance.</param>
		/// <param name="query">The query.</param>
		/// <param name="parameterValues">The parameter values.</param>
		/// <param name="progress">The progress.</param>
		/// <returns>
		/// The <see cref="QueryInstanceResultInfo" />.
		/// </returns>
		private QueryInstanceResultInfo ExecuteQuery(
			InstanceInfo         instance,
			QueryInfo            query,
			QueryExecutionParams parameters,
			ProgressItem         progress = null
		)
		{
			try
			{
				var factory = new QueryExecutorFactory(instance, this.ExecuteQueryItem, this.ExecuteSql);

				CurrentStorage storage = this._model.GetVaultProcessor(
					instance.ConnectionGroup).CurrentStorage;

				ServerProperties props = instance.InitServerProperties(storage);
				return factory
					.GetExecutor(query.Scope)
					.ExecuteQuery(query, parameters, props.Version, progress);
			}
			catch (OperationCanceledException ex)
			{
				return new QueryInstanceResultInfo(new ErrorInfo(ex), instance);
			}
			catch (Exception ex)
			{
				if (instance.IsEnabled && !ex.Data.Contains("IgnoreLog"))
				{
					log.Error(query.ToString(), ex);
				}

				if (progress != null)
				{
					progress.SetProgressCanceled();
				}

				return new QueryInstanceResultInfo(new ErrorInfo(ex), instance);
			}
		}
コード例 #7
0
		private QueryResultInfo ExecuteQuery(
			GroupDefinition      groupDefinition,
			QueryInfo            query,
			QueryExecutionParams parameters,
			ProgressItem         progress = null
		)
		{
			QueryResultInfo queryResult = new QueryResultInfo();
			InstanceInfo instance       = groupDefinition.Instance;

			QueryExecutorFactory factory = new QueryExecutorFactory(
				instance,
				this.ExecuteQueryItem,
				this.ExecuteSql
			);

			BaseQueryExecutor executor = factory.GetExecutor(
				query.Scope
			);

			CurrentStorage storage = this._model.GetVaultProcessor(
				instance.ConnectionGroup).CurrentStorage;

			ServerProperties props = instance.InitServerProperties(storage);
			QueryInstanceResultInfo instanceResult = executor.ExecuteQuerySimple(
				query,
				parameters,
				props.Version,
				progress,
				groupDefinition
			);

			queryResult.AddInstanceResult(instanceResult);

			return queryResult;
		}
コード例 #8
0
		public QueryInstanceResultInfo GetConnectionSelectResults(
			InstanceInfo          selectConnectionInstance,
			QueryInfo             queryInfo,
			QueryItemInfo         queryItem,
			TemplateNodeQueryInfo query
		)
		{
			QueryDatabaseResultInfo dbResultInfo;

			try
			{
				DataTable[] tables = ExecuteSql(
					selectConnectionInstance,
					queryItem,
					query.TemplateNode.GetDefaultDatabase(),
					queryInfo.Parameters,
					query.ParameterValues
				);

				if (tables != null && tables.Length < 0)
				{
					throw new InvalidTemplateException(query + " returned no recordsets.");
				}

				dbResultInfo = new QueryDatabaseResultInfo(tables, queryItem);
			}
			catch (Exception exc)
			{
				ErrorInfo error = new ErrorInfo(exc);

				dbResultInfo = new QueryDatabaseResultInfo(error, queryItem);
			}

			QueryInstanceResultInfo instanceResultInfo = new QueryInstanceResultInfo(selectConnectionInstance);

			instanceResultInfo.AddDatabaseResult(dbResultInfo);

			return instanceResultInfo;
		}
コード例 #9
0
		public DataTable[] GetGroupSelectResultsFromServer(
			SqlProcessor          sqlProcessor,
			InstanceInfo          serverInstance,
			QueryInfo             queryInfo,
			TemplateNodeQueryInfo query
		)
		{
			DataTable[] tables = null;
			ErrorInfo   error  = null;

			Debug.Assert(IsInstance);
			Debug.Assert(GroupQueries.Contains(query));

			var db = this._model.GetVaultProcessor(ConnectionGroup).CurrentStorage;

			InstanceTemplate settings = GetUserSettings();

			//looking for user settings for parameter values
			query.ReadParametersFrom(settings);

			try
			{
				tables = sqlProcessor.ExecuteSql(
					serverInstance,
					queryInfo,
					GetDefaultDatabase(),
					queryInfo.Parameters,
					query.ParameterValues,
					fromGroupSelect: true
				);
			}
			catch (Exception ex)
			{
				error  = new ErrorInfo(ex);
				tables = null;
			}

			Int64? queryId = db.QueryGroupDirectory.GetQueryId(
				query.TemplateNode,
				query,
				serverInstance,
				DateTime.Now,
				false
			);

			db.SaveMeta(queryId, error, tables);

			if (tables != null && tables.Length < 0)
			{
				throw new InvalidTemplateException(query + " returned no recordsets.");
			}

			return tables;
		}