Exemplo n.º 1
0
        public void BulkLoadDestinationTables()
        {
            var sourceQueryRunner = new QueryRunner(tableSet.SourceConnectionStringName);

            foreach (var tableMap in tableSet.Mappings.Where(ts=>ts.TruncateDestinationAndBulkLoadFromSource).OrderBy(ts => ts.Ordinal))
            {
                var query = syncChangesData.BuildQueryToRemoveChangesForTable(tableMap.SourceSchema, tableMap.SourceTable);
                sourceQueryRunner.RunQuery(query);

                Logging.WriteMessageToApplicationLog("About to bulk load data from " + tableMap.FullyQualifiedSourceTable + " to " + tableMap.FullyQualifiedDestinationTable, EventLogEntryType.Information);
                using (var bulkCopy = new SqlBulkCopy(DestinationConnectionString, SqlBulkCopyOptions.KeepIdentity))
                {
                    bulkCopy.DestinationTableName = tableMap.FullyQualifiedDestinationTable;
                    bulkCopy.EnableStreaming = true;
                    bulkCopy.BulkCopyTimeout = BulkCopyTimeout;
                    using (var conn = openSourceConnection())
                    {
                        var sql = "select * from " + tableMap.FullyQualifiedSourceTable + ";";
                        if (!string.IsNullOrEmpty(tableMap.CustomSourceSQLForBulkLoadOnly))
                        {
                            sql = tableMap.CustomSourceSQLForBulkLoadOnly;
                        }
                        var command = createCommand(conn, sql);
                        command.CommandTimeout = BulkCopyTimeout;
                        using (var reader = command.ExecuteReader())
                        {
                            bulkCopy.WriteToServer(reader);
                        }
                    }
                    bulkCopy.Close();
                }
            }
        }
Exemplo n.º 2
0
        public void TestGetAllScript()
        {
            QueryRunner runner = new QueryRunner();
            List<AddressBook> addresses = runner.GetAll<AddressBook>();

            Assert.AreEqual(3, addresses.Count);
        }
Exemplo n.º 3
0
        public void TestGetByAttribute()
        {
            QueryRunner runner = new QueryRunner();
            List<AddressBook> addresses = runner.GetByAttribute<AddressBook>("Robert", typeof(Name));

            Assert.AreEqual(1, addresses.Count);
        }
Exemplo n.º 4
0
 public SyncStatusReport(TableSet tableSet)
 {
     this.tableSet = tableSet;
     sourceDB = new QueryRunner(tableSet.SourceConnectionStringName);
     destinationDB = new QueryRunner(tableSet.DestinationConnectionStringName);
     restClient = new RestClient(BaseUrl);
 }
Exemplo n.º 5
0
 public DbSyncProvider(TableSet tableSet)
 {
     this.tableSet = tableSet;
     sourceDb = new QueryRunner(tableSet.SourceConnectionStringName);
     destinationDB = new QueryRunner(tableSet.DestinationConnectionStringName);
     syncChangesData = new SyncChangesData(tableSet);
 }
Exemplo n.º 6
0
        public void TestExecuteScript()
        {
            string query = "select * from AddressBook";

            QueryRunner runner = new QueryRunner();
            List<AddressBook> addresses = runner.Execute<AddressBook>(query);

            Assert.AreEqual(3, addresses.Count);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Globals the advert message.
        /// </summary>
        /// <param name="message">The message.</param>
        protected void GlobalAdvertMessage(MessageDefinition message)
        {
            if (!message.Enabled)
            {
                return;
            }

            if (Repository.Static.GetLastIntervalById(message.Id).AddMinutes(message.Interval) < Repository.Static.Now)
            {
                Repository.Static.SetLastIntervalById(message.Id, Repository.Static.Now);
                QueryRunner.SendGlobalMessage(message.TextMessage.ToMessage());

                Log(message, string.Format("Global advert message successfully sent."));
            }
        }
Exemplo n.º 8
0
        public void CartesianProduct()
        {
            // Asserts if the query result for a relationship join operation is equal
            // to a handcrafted query
            RequiredDataContainer ModelData = CartesianProductDataProvider.SampleData();

            // Load handcrafted query
            string HandcraftedQuery = Utils.ReadQueryFromFile("HandcraftedQueries/cartersianProduct-1.js");

            // Assert if the handcrafted query is not null
            Assert.IsNotNull(HandcraftedQuery);

            // Prepare query generator
            CartesianProductOperator CartesianOp = new CartesianProductOperator(
                new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person"), "person"),
                new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Car"), "car"),
                ModelData.ERMongoMapping);

            CartesianProductOperator CartesianOp2 = new CartesianProductOperator(
                new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person"), "person"),
                new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Supplier"), "supplier"),
                ModelData.ERMongoMapping);

            FromArgument StartArg = new FromArgument(new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person")),
                                                     ModelData.ERMongoMapping);
            QueryGenerator QueryGen = new QueryGenerator(StartArg, new List <AlgebraOperator>()
            {
                CartesianOp, CartesianOp2
            });

            string GeneratedQuery = QueryGen.Run();

            // Assert if generated query is not null
            Assert.IsNotNull(GeneratedQuery);

            // Run Queries
            QueryRunner Runner = new QueryRunner("mongodb://localhost:27017", "ceManyToMany2");

            string HandcraftedResult = Runner.GetJSON(HandcraftedQuery);
            string GeneratedResult   = Runner.GetJSON(GeneratedQuery);

            // Check if either result is null
            Assert.IsNotNull(HandcraftedResult);
            Assert.IsNotNull(GeneratedResult);

            // Check if both results are equal
            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(HandcraftedResult), JToken.Parse(GeneratedResult)));
        }
Exemplo n.º 9
0
        public override List <SkinnyItem> GetItems(string databaseName,
                                                   string indexName,
                                                   string language,
                                                   string templateFilter,
                                                   bool searchBaseTemplates,
                                                   string locationFilter,
                                                   string fullTextQuery)
        {
            var baseCondition = GetCondition(this.BaseConditionList);
            var outerNumParamParamCondition = GetCondition(this.InnerNumericRangeConditionList);
            var outerDateParamCondition     = GetCondition(this.InnerDateRangeConditionList);
            var innerNumParamParamCondition = GetCondition(this.InnerNumericRangeConditionList);
            var innerDateParamCondition     = GetCondition(this.InnerDateRangeConditionList);

            var parameters = new List <SearchParam>
            {
                new SearchParam
                {
                    Database            = databaseName,
                    LocationIds         = locationFilter,
                    TemplateIds         = templateFilter,
                    SearchBaseTemplates = searchBaseTemplates,
                    FullTextQuery       = fullTextQuery,
                    Language            = language,
                    Condition           = baseCondition
                },
                new NumericRangeSearchParam
                {
                    Ranges         = this.NumericRanges,
                    InnerCondition =
                        innerNumParamParamCondition,
                    Condition =
                        outerNumParamParamCondition
                },
                new DateRangeSearchParam
                {
                    Ranges         = this.DateRanges,
                    InnerCondition =
                        innerDateParamCondition,
                    Condition = outerDateParamCondition
                }
            };

            using (var runner = new QueryRunner(indexName))
            {
                return(runner.GetItems(parameters));
            }
        }
Exemplo n.º 10
0
        public Task Terms()
        {
            var name      = GetQueryStringValueAndAssertIfSingleAndNotEmpty("name");
            var field     = GetQueryStringValueAndAssertIfSingleAndNotEmpty("field");
            var fromValue = GetStringQueryString("fromValue", required: false);

            DocumentsOperationContext context;

            using (var token = CreateTimeLimitedOperationToken())
                using (Database.DocumentsStorage.ContextPool.AllocateOperationContext(out context))
                    using (context.OpenReadTransaction())
                    {
                        var existingResultEtag = GetLongFromHeaders("If-None-Match");

                        var runner = new QueryRunner(Database, context);

                        var result = runner.ExecuteGetTermsQuery(name, field, fromValue, existingResultEtag, GetPageSize(Database.Configuration.Core.MaxPageSize), context, token);

                        if (result.NotModified)
                        {
                            HttpContext.Response.StatusCode = (int)HttpStatusCode.NotModified;
                            return(Task.CompletedTask);
                        }

                        HttpContext.Response.Headers[Constants.MetadataEtagField] = result.ResultEtag.ToInvariantString();

                        using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                        {
                            writer.WriteStartArray();
                            var isFirst = true;
                            foreach (var term in result.Terms)
                            {
                                if (isFirst == false)
                                {
                                    writer.WriteComma();
                                }

                                isFirst = false;

                                writer.WriteString((term));
                            }

                            writer.WriteEndArray();
                        }

                        return(Task.CompletedTask);
                    }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Moves the idle clients back.
        /// </summary>
        protected void MoveIdleClientsBack()
        {
            if (!Repository.Settings.Idle.Enabled)
            {
                return;
            }

            foreach (var client in Repository.Client.GetClientList()
                     .Where(m => m.ChannelId == Repository.Settings.Idle.Channel &&          // Check for Channel
                            !m.IsAway(Repository.Settings.Away) &&                           // Check if not away (to prevent endless loop)
                            !m.IsInputMuted(Repository.Settings.Away) &&                     // Check if not muted Microphone
                            !m.IsOutputMuted(Repository.Settings.Away) &&                    // Check if not muted Headphones
                            !m.IsIdle(Repository.Settings.Idle) &&                           // Check if not idle
                            Repository.Client.HasLastChannelByClientId(m.ClientDatabaseId))) // Check for last-channel entry
            {
                if (!Repository.Channel.GetClientSticky(client.ClientDatabaseId).HasValue)
                {
                    var idleClient = Repository.Client.GetLastChannelByClientId(client.ClientDatabaseId);
                    if (idleClient != default(AwayClientEntity))
                    {
                        var channel = Repository.Channel.GetChannelListInfo((uint)idleClient.LastChannelId) ?? new ChannelListEntry();
                        QueryRunner.MoveClient(client.ClientId, (uint)idleClient.LastChannelId);

                        Log(Repository.Settings.Idle,
                            string.Format("Client '{0}'(id:{1}) successfully moved back from Idle Channel to '{2}'(id:{3}).",
                                          client.Nickname, client.ClientDatabaseId, channel.Name, idleClient.LastChannelId));

                        if (!string.IsNullOrEmpty(Repository.Settings.Idle.TextMessage))
                        {
                            var idleTimespan   = Repository.Static.Now - idleClient.Creation;
                            var messageContext = new MessageContext
                            {
                                ClientDatabaseId = client.ClientDatabaseId,
                                ClientNickname   = client.Nickname,
                                ClientAwayTime   = BasicHelper.GetTimespanString(idleTimespan),
                                ChannelId        = (uint)idleClient.LastChannelId,
                                ChannelName      = channel.Name
                            };
                            if (Repository.Connection.CredentialEntity.Self != null)
                            {
                                QueryRunner.SendTextMessage(MessageTarget.Server, Repository.Connection.CredentialEntity.Self.VirtualServerId, Repository.Settings.Idle.TextMessage.ToMessage(messageContext));
                            }
                        }
                    }
                }
                Repository.Client.RemoveLastChannelByClientId(client.ClientDatabaseId);
            }
        }
Exemplo n.º 12
0
        public void GetAllProductsFromCategoryWithUserAndSelectOnlyTitleNameEmailCategoryName()
        {
            var DataMap                   = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/MarketingCMS/entities-to-collections.mapping"));
            var DataMapDuplicates         = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/MarketingCMS/entities-to-collections-duplicates.mapping"));
            var DataMapCategoryDuplicated = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/MarketingCMS/entities-to-collections-category-duplicated.mapping"));
            var DataMapStoreDuplicated    = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/MarketingCMS/entities-to-collections-store-duplicated.mapping"));
            var DataMapUserDuplicated     = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/MarketingCMS/entities-to-collections-user-duplicated.mapping"));

            string QueryString = "from Category rjoin <CategoryProducts> (Product rjoin <UserProducts> (User)) select Product.Title, User.UserName, User.UserEmail, Category.CategoryName";

            QueryGenerator GeneratorMap1 = QueryBuilderParser.ParseQuery(QueryString, DataMap);
            QueryGenerator GeneratorMap2 = QueryBuilderParser.ParseQuery(QueryString, DataMapDuplicates);
            QueryGenerator GeneratorMap3 = QueryBuilderParser.ParseQuery(QueryString, DataMapCategoryDuplicated);
            QueryGenerator GeneratorMap4 = QueryBuilderParser.ParseQuery(QueryString, DataMapStoreDuplicated);
            QueryGenerator GeneratorMap5 = QueryBuilderParser.ParseQuery(QueryString, DataMapUserDuplicated);

            string QueryMap1 = GeneratorMap1.Run();

            Assert.ThrowsException <ImpossibleOperationException>(GeneratorMap2.Run);
            Assert.ThrowsException <ImpossibleOperationException>(GeneratorMap3.Run);
            string QueryMap4 = GeneratorMap4.Run();
            string QueryMap5 = GeneratorMap5.Run();

            Assert.IsNotNull(QueryMap1, "Query [Map1] cannot be null");
            Assert.IsNotNull(QueryMap4, "Query [Map4] cannot be null");
            Assert.IsNotNull(QueryMap5, "Query [Map5] cannot be null");

            QueryRunner RunnerMap1 = new QueryRunner("mongodb://localhost:27017", "pesquisa_cms");
            QueryRunner RunnerMap4 = new QueryRunner("mongodb://localhost:27017", "pesquisa_cms_store_duplicado");
            QueryRunner RunnerMap5 = new QueryRunner("mongodb://localhost:27017", "pesquisa_cms_user_duplicado");

            string ResultMap1 = RunnerMap1.GetJSON(QueryMap1);
            string ResultMap4 = RunnerMap4.GetJSON(QueryMap4);
            string ResultMap5 = RunnerMap5.GetJSON(QueryMap5);

            Assert.IsNotNull(ResultMap1, "Result [Map1] cannot be null");
            Assert.IsNotNull(ResultMap4, "Result [Map4] cannot be null");
            Assert.IsNotNull(ResultMap5, "Result [Map5] cannot be null");

            Assert.IsTrue(ResultMap1 != string.Empty, "Result [Map1] cannot be empty");
            Assert.IsTrue(ResultMap4 != string.Empty, "Result [Map4] cannot be empty");
            Assert.IsTrue(ResultMap5 != string.Empty, "Result [Map5] cannot be empty");

            JToken TokenResult1 = JToken.Parse(ResultMap1);

            TokenResult1.Should().BeEquivalentTo(JToken.Parse(ResultMap4));
            TokenResult1.Should().BeEquivalentTo(JToken.Parse(ResultMap5));
        }
Exemplo n.º 13
0
        public static void muteUnmuteRTP(bool state)
        {
            // Get the host address, username and port for the ServerQuery Login
            Dictionary <string, string> config = getTSInfo();

            if (config == null)
            {
                return;
            }

            string sqPW = getSQPassword();
            ushort port;
            uint   talkPwr = (uint)(state ? 50 : 0);

            Regex regex = new Regex(@"^[0-9]+$");

            if (regex.IsMatch(config["port"]))
            {
                port = Convert.ToUInt16(config["port"]);
            }
            else
            {
                string msg = "ERROR: Invalid port. Port number may contain numbers 1-9 only.";
                string cap = "Error";
                errorMSG(msg, cap);
                return;
            }

            // Establish a connection with the TS3 server
            using (QueryRunner QR = new QueryRunner(new SyncTcpDispatcher(config["addr"], port)))
            {
                if (loginAndUse(QR, config, sqPW) != null)
                {
                    SimpleResponse muteResponse = QR.EditChannel(CID_RTP,
                                                                 new ChannelModification()
                    {
                        NeededTalkPower = talkPwr
                    });

                    if (muteResponse.IsErroneous)
                    {
                        string muteMsg = $"ERROR: {muteResponse.ErrorMessage}\n\n Error ID: {muteResponse.ErrorId}";
                        string muteCap = "Mute Channel Failed";
                        errorMSG(muteMsg, muteCap);
                    }
                }
            }
        }
        public void OneToOneRelationshipAttributesMultipleRoots()
        {
            // Asserts if the query result for a simple binary join is equal
            // to a handcrafted query
            RequiredDataContainer ModelData = OneToOneRelationshipsDataProvider.OneToOneRelationshipMultipleRootAttributes();

            // Load handcrafted query
            string HandcraftedQuery = Utils.ReadQueryFromFile("HandcraftedQueries/personCarOneToOneMultipleRootAttributes.js");

            // Assert if the handcrafted query is not null
            Assert.IsNotNull(HandcraftedQuery);

            // Prepare query generator
            RelationshipJoinOperator RJoinOp = new RelationshipJoinOperator(
                new QueryableEntity(( Entity)ModelData.EntityRelationshipModel.FindByName("Person"), "person"),
                (Relationship)ModelData.EntityRelationshipModel.FindByName("HasInsurance"),
                new List <QueryableEntity> {
                new QueryableEntity((Entity)ModelData.EntityRelationshipModel.FindByName("Car"), "car"),
                new QueryableEntity((Entity)ModelData.EntityRelationshipModel.FindByName("Insurance"), "insurance")
            },
                ModelData.ERMongoMapping);

            List <AlgebraOperator> OpList = new List <AlgebraOperator> {
                RJoinOp
            };
            FromArgument StartArg = new FromArgument(new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person")),
                                                     ModelData.ERMongoMapping);

            QueryGenerator QueryGen = new QueryGenerator(StartArg, OpList);

            string GeneratedQuery = QueryGen.Run();

            // Assert if generated query is not null
            Assert.IsNotNull(GeneratedQuery);

            // Run Queries
            QueryRunner Runner = new QueryRunner("mongodb://localhost:27017", "researchOneToOneMultipleRoots");

            string HandcraftedResult = Runner.GetJSON(HandcraftedQuery);
            string GeneratedResult   = Runner.GetJSON(GeneratedQuery);

            // Check if either result is null
            Assert.IsNotNull(HandcraftedResult);
            Assert.IsNotNull(GeneratedResult);

            // Check if both results are equal
            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(HandcraftedResult), JToken.Parse(GeneratedResult)));
        }
        /// <summary>The tool strip button test_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void toolStripButtonTest_Click(object sender, EventArgs e)
        {
            // do a standalone raw connection test
            Exception exp = QueryRunner.TestDbConnection(ProviderName, ConnectionString);

            if (exp == null)
            {
                string msg = string.Format(Resources.Connected_to_0_successfully, ConnectionName);
                _hostWindow.DisplaySimpleMessageBox(this, msg, Resources.Connection_Successful);
            }
            else
            {
                string msg = string.Format(Resources.Failed_connecting_to_0_1_2, ConnectionName, Environment.NewLine, exp.Message);
                _hostWindow.DisplaySimpleMessageBox(this, msg, Resources.Connection_Failed);
            }
        }
Exemplo n.º 16
0
        private void QueryDispatcher_ReadyForSendingCommands(object sender, EventArgs e)
        {
            UpdateUI(ConnectionState.Connected);
            // you can only run commands on the queryrunner when this event has been raised first!
            QueryRunner = new QueryRunner(QueryDispatcher);

            VersionResponse versionResponse = QueryRunner.GetVersion();

            if (versionResponse.IsErroneous)
            {
                MessageBox.Show("Could not get server version: " + versionResponse.ErrorMessage);
                return;
            }

            MessageBox.Show(string.Format("Server version:\n\nPlatform: {0}\nVersion: {1}\nBuild: {2}", versionResponse.Platform, versionResponse.Version, versionResponse.Build));
        }
Exemplo n.º 17
0
        public void GetAllStatuses_ReturnsResults_IgnoresExtraProperty()
        {
            DatabaseBootstrapper.CreateAndPopulate();

            DataTable dataTable = QueryRunner.ExecuteStoredProcedure("uspGetAllStatuses");

            DatabaseBootstrapper.Drop();

            DataTableConverter dtp = new DataTableConverter();

            dtp.DataTableParserSettings.MissingMappingHandling = MissingMappingHandling.Ignore;

            var results = dtp.ConvertToObjectList <StatusExtraProperty>(dataTable);

            Assert.Equal(dataTable.Rows.Count, results.Count());
        }
Exemplo n.º 18
0
        public void GetAllStatuses_ReturnsResults_CanBeParsedWithCorrectObjects()
        {
            DatabaseBootstrapper.CreateAndPopulate();

            DataTable dataTable = QueryRunner.ExecuteStoredProcedure("uspGetAllStatuses");

            DatabaseBootstrapper.Drop();

            DataTableConverter dtp = new DataTableConverter();

            var results = dtp.ConvertToObjectList <StatusPropertyNamesMatch>(dataTable);

            Assert.True(results.Where(r => r.Id == (int)dataTable.Rows[0]["Id"] &&
                                      r.Description == dataTable.Rows[0]["Description"].ToString() &&
                                      r.IsPublic == (bool)dataTable.Rows[0]["IsPublic"]).Count() == 1);
        }
Exemplo n.º 19
0
        private void DoQuery(object sender, DoWorkEventArgs e)
        {
            var txt = RequestSelectedQueryText();

            if (string.IsNullOrEmpty(txt))
            {
                txt = QueryText;
            }

            var runner = new QueryRunner(Result, Application.Current.Dispatcher);

            using (var logWriter = Output.StartStopwatchWriter())
            {
                runner.Run(_assemblyFileNames, txt, logWriter);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Receives the Help message
        /// </summary>
        /// <param name="message">The message.</param>
        private void Execute(HelpMessage message)
        {
            var helpMessages = MessageHelper.GetHelpMessages(Repository.Client.GetClientInfo(message.SenderClientId).ServerGroups);

            if (helpMessages != null)
            {
                helpMessages.ForEach(helpMessage => QueryRunner.SendTextMessage(Repository.Settings.Control.Help.Target, Repository.Settings.Control.Help.TargetId > 0 ? Repository.Settings.Control.Help.TargetId : message.SenderClientId,
                                                                                helpMessage.ToMessage()));
            }

            var clientEntry = Repository.Client.GetClientInfo(message.SenderClientId);

            Log(Repository.Settings.Control.Help,
                string.Format("Client '{1}'(id:{2}) used {0}.", Repository.Settings.Control.Help.Command,
                              clientEntry.Nickname, clientEntry.DatabaseId));
        }
 /// <summary>
 /// This will keep the connection to the telnet server alive
 /// Checks if you are connected to teamspeak and to a server and will reset the timer
 /// else
 /// Try reconnecting
 /// </summary>
 private void time_Elapsed(object sender, ElapsedEventArgs e)
 {
     if (Connected == ConnectionState.Connected && !(currentUser = QueryRunner.SendWhoAmI()).IsErroneous)
     {
         currentUser = QueryRunner.SendWhoAmI();
         //API.Log(API.LogType.Debug, "Teamspeak.ddl: server_keep_alive_message");
     }
     else
     {
         if (!Retry_Connection_Timer.Enabled)
         {
             Retry_Connection_Timer.Start();
         }
         Keep_Alive_Timer.Stop();
     }
 }
        public void Store(QueryRunner QueryRunner, List <ChannelListEntry> ChannelList, ChannelInfoResponse ChannelInfo, ChannelListEntry Channel, Action <int, ChannelInfoResponse, ChannelListEntry> StoreMethod)
        {
            this.QueryRunner = QueryRunner;
            this.Parse(ChannelInfo, Channel);

            for (int i = 0; i < ChannelList.Count; i++)
            {
                if (ChannelList[i].ParentChannelId == Channel.ChannelId)
                {
                    var SubChannelInfo = QueryRunner.GetChannelInfo(ChannelList[i].ChannelId);
                    SubChannels.Add(new ChannelWithSubChannelsPackager(this.SubscriberId, this.SubscriberUniqueId, QueryRunner, ChannelList, SubChannelInfo, ChannelList[i], StoreMethod));
                }
            }

            StoreMethod.Invoke((int)this.ChannelId, ChannelInfo, Channel);
        }
Exemplo n.º 23
0
        public void TestIntegrationOneToManyMapperQuery()
        {
            var queryRunner = QueryRunner.CreateHelper("SqlAdoHelper", new QueryMapper());
            var users       = queryRunner.Execute <SimpleDto>(new QueryOneToMany()).ToList();

            Assert.IsNotNull(users);
            // ReSharper disable PossibleMultipleEnumeration
            Assert.AreEqual(2, users.Count());

            var user = users.First();

            // ReSharper restore PossibleMultipleEnumeration

            Assert.IsNotNull(user.Phones);
            Assert.AreEqual(2, user.Phones.Count());
        }
Exemplo n.º 24
0
    static Task <AttachmentExecutionResult> RunQuery(string queryString)
    {
        var incomingAttachments = new IncomingAttachments();
        var stream   = BuildStream();
        var metadata = new HeaderDictionary
        {
            { "header1", "headerValue" }
        };

        incomingAttachments.Add("key", new AttachmentStream("key", stream, 3, metadata));
        var services = new ServiceCollection();

        TestServices.AddGraphQlTestTypes(services);

        return(QueryRunner.ExecuteQuery(queryString, services, incomingAttachments));
    }
Exemplo n.º 25
0
            public override void BuildQuery <T>(Query <T> query, ParameterExpression queryParameter)
            {
                var sql = GetSubQuery(null);

                var sq = new SqlSelectStatement();

                sq.SelectQuery.Select.Add(sql);

                query.Queries[0].Statement = sq;

                var expr   = Builder.BuildSql(typeof(bool), 0, sql);
                var mapper = Builder.BuildMapper <object>(expr);

                CompleteColumns();
                QueryRunner.SetRunQuery(query, mapper);
            }
Exemplo n.º 26
0
        /// <summary>
        /// Executes the Moderator message.
        /// </summary>
        /// <param name="message">The message.</param>
        private void Execute(ModeratorMessage message)
        {
            if (message.ErrorMessage != null)
            {
                Log(LogLevel.Warning, message.ErrorMessage);
                return;
            }

            var server   = Repository.Server.GetCurrentServer();
            var entities = Repository.Client.GetModeration(ModerationType.Added, message.TimeSpan.FromDate, message.TimeSpan.ToDate);

            var context = new MessageContext
            {
                ServerId   = server.Id,
                ServerName = server.Name,
                ServerPort = server.Port
            };

            QueryRunner.SendTextMessage(Repository.Settings.Control.Moderator.Target, Repository.Settings.Control.Moderator.TargetId > 0 ? Repository.Settings.Control.Moderator.TargetId : message.SenderClientId,
                                        Repository.Settings.Control.Moderator.TextMessage.ToMessage(context));
            var groupedEntities = entities.GroupBy(m => m.ModeratorDatabaseId).OrderByDescending(m => m.Count()).Take(Repository.Settings.Control.Moderator.Limit).ToList();

            for (int index = 0; index < groupedEntities.Count; index++)
            {
                var entity          = groupedEntities[index];
                var moderatorEntity = Repository.Client.GetClientDataBaseInfo((uint)entity.Key);
                var messageContext  = new MessageContext
                {
                    Index             = index + 1,
                    ServerName        = server.Name,
                    ServerId          = server.Id,
                    ServerPort        = server.Port,
                    ClientDatabaseId  = moderatorEntity == null ? default(uint) : moderatorEntity.DatabaseId,
                    ClientNickname    = moderatorEntity == null ? default(string) : moderatorEntity.NickName,
                    ModeratorVerified = entity.Count()
                };
                QueryRunner.SendTextMessage(Repository.Settings.Control.Moderator.Target,
                                            Repository.Settings.Control.Moderator.TargetId > 0 ? Repository.Settings.Control.Moderator.TargetId : message.SenderClientId,
                                            Repository.Settings.Control.Moderator.MessagePerModerator.ToMessage(messageContext));
            }

            var clientEntry = Repository.Client.GetClientInfo(message.SenderClientId);

            Log(Repository.Settings.Control.Moderator,
                string.Format("Client '{1}'(id:{2}) used {0}.", Repository.Settings.Control.Moderator.Command,
                              clientEntry.Nickname, clientEntry.DatabaseId));
        }
Exemplo n.º 27
0
        public static void modalMessage(bool mode)
        {
            // Get the host address, username and port for the ServerQuery Login
            Dictionary <string, string> config = getTSInfo();

            if (config == null)
            {
                return;
            }

            string sqPW = getSQPassword();
            ushort port;

            Regex regex = new Regex(@"^[0-9]+$");

            if (regex.IsMatch(config["port"]))
            {
                port = Convert.ToUInt16(config["port"]);
            }
            else
            {
                string msg = "ERROR: Invalid port. Port number may contain numbers 1-9 only.";
                string cap = "Error";
                errorMSG(msg, cap);
                return;
            }

            // Establish a connection with the TS3 server
            using (QueryRunner QR = new QueryRunner(new SyncTcpDispatcher(config["addr"], port)))
            {
                if (loginAndUse(QR, config, sqPW) != null)
                {
                    SimpleResponse modalResponse = QR.EditServer(new VirtualServerModification()
                    {
                        HostMessageMode = mode ? HostMessageMode.HostMessageModeModal : HostMessageMode.HostMessageModeNone
                    });

                    if (modalResponse.IsErroneous)
                    {
                        string muteMsg = $"ERROR: {modalResponse.ErrorMessage}\n\n Error ID: {modalResponse.ErrorId}";
                        string muteCap = "Failed to edit Host Message Mode";
                        errorMSG(muteMsg, muteCap);
                    }
                }
            }
        }
Exemplo n.º 28
0
        private void Disconnect()
        {
            lock (this)
            {
                if (Connected)
                {
                    _pluginManager.Dispose();
                    QueryDispatcher.Disconnect();
                    QueryDispatcher?.Dispose();
                    QueryRunner?.Dispose();

                    _stopwatch.Stop();
                    Console.WriteLine("Disconnected! Been connected for {0}:{1}:{2}.{3}", _stopwatch.Elapsed.Hours, _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds);
                }
                Connected = false;
            }
        }
Exemplo n.º 29
0
        private ActionResult GetCsv(string sitename, int revisionId, TargetSites targetSites)
        {
            Query query = QueryUtil.GetQueryForRevision(revisionId);

            if (query == null)
            {
                return(PageNotFound());
            }

            var results = QueryRunner.GetResults(
                new ParsedQuery(query.QueryBody, Request.Params, executionPlan: false, targetSites: targetSites),
                null,
                CurrentUser
                );

            return(new CsvResult(results.ResultSets));
        }
        public ActionResult ShowSingleSiteCsv(string sitename, int revisionId, string slug)
        {
            Query query = QueryUtil.GetQueryForRevision(revisionId);

            if (query == null)
            {
                return(PageNotFound());
            }

            Site site;

            if (!TryGetSite(sitename, out site))
            {
                return(site == null ?  (ActionResult)PageNotFound() : RedirectPermanent(string.Format("/{0}/csv/{1}{2}{3}",
                                                                                                      site.TinyName.ToLower(), revisionId, slug.HasValue() ? "/" + slug : "", Request.Url.Query
                                                                                                      )));
            }

            var parsedQuery = new ParsedQuery(query.QueryBody, Request.Params);

            if (!parsedQuery.IsExecutionReady)
            {
                return(PageBadRequest());
            }

            CachedResult cachedResults = QueryUtil.GetCachedResults(
                parsedQuery,
                Site.Id
                );
            List <ResultSet> resultSets;

            if (cachedResults != null)
            {
                resultSets = JsonConvert.DeserializeObject <List <ResultSet> >(cachedResults.Results, QueryResults.GetSettings());
            }
            else
            {
                resultSets = QueryRunner.GetResults(
                    parsedQuery,
                    site,
                    CurrentUser
                    ).ResultSets;
            }

            return(new CsvResult(resultSets));
        }
Exemplo n.º 31
0
        public void SimpleSelectAllQuery()
        {
            using(var connection = new SQLiteConnection("Data Source=testdb.db;Version=3;Read Only=True;"))
            {
                connection.Open();

                var dialect = new Dialect.SQLiteDialect();
                var runner = new QueryRunner(connection, dialect);

                var query = new SqlQuery<Order>();

                var results = runner.ExecuteReader(query).ToList();

                Assert.AreEqual(10, results.Count);
                results.Select(order => order.Id).AssertSeqeuenceEquals(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Receives the Seen message
        /// </summary>
        /// <param name="message">The message.</param>
        private void Execute(SeenMessage message)
        {
            if (message.ErrorMessage != null)
            {
                Log(LogLevel.Warning, message.ErrorMessage);
                return;
            }

            if (message.ClientDatabaseIds.Count == 1 &&
                message.ClientDatabaseIds.Contains(Self.ClientDatabaseId))
            {
                return;
            }

            for (int index = 0; index < message.ClientDatabaseIds.Count; index++)
            {
                var clientDatabaseId = message.ClientDatabaseIds[index];
                var client           = Repository.Client.GetClientDataBaseInfo(clientDatabaseId);
                if (client != null)
                {
                    var lastSeen = Repository.Client.GetLastSeen(clientDatabaseId);
                    var context  = new MessageContext
                    {
                        Index            = index + 1,
                        ClientDatabaseId = client.DatabaseId,
                        ClientNickname   = client.NickName,
                        ClientLastLogin  = client.LastConnected.ToLocalTime().ToString(Repository.Static.DateTimeFormat),
                        ClientLastSeen   = lastSeen != default(DateTime) && lastSeen > DateTime.MinValue
                                                               ? lastSeen.ToLocalTime().ToString(Repository.Static.DateTimeFormat)
                                                               : client.LastConnected.ToLocalTime().ToString(Repository.Static.DateTimeFormat)
                    };

                    QueryRunner.SendTextMessage(Repository.Settings.Control.Seen.Target,
                                                Repository.Settings.Control.Seen.TargetId > 0 ? Repository.Settings.Control.Seen.TargetId : message.SenderClientId,
                                                Repository.Settings.Control.Seen.TextMessage.ToMessage(context));
                }
            }

            var senderClientEntry = Repository.Client.GetClientInfo(message.SenderClientId);

            Log(Repository.Settings.Control.Seen,
                string.Format("Client '{1}'(id:{2}) used {0} for clients '{3}'.", Repository.Settings.Control.Seen.Command,
                              senderClientEntry.Nickname, senderClientEntry.DatabaseId,
                              string.Join("', '", message.ClientDatabaseIds.ConvertAll(i => i.ToString(CultureInfo.InvariantCulture)).ToArray())));
        }
        public void QueryRunner_SingleTerm()
        {
            Mock <IIndex> indexMock = new Mock <IIndex>();

            indexMock.Setup(m => m.PostingsLists(It.Is <string>(x => x == "test"))).Returns(PostingListResult("test", new List <int> {
                1, 2, 4, 5, 6, 8, 9
            }));
            indexMock.Setup(m => m.PostingsLists(It.Is <string>(x => x == "example"))).Returns(PostingListResult("example", new List <int> {
                2, 4, 6, 7, 9, 10
            }));

            var queryRunner = new QueryRunner(indexMock.Object);

            var result = queryRunner.Query("example");

            Assert.AreEqual(6, result.Count);
            Assert.AreEqual(7, result[3]);
        }
Exemplo n.º 34
0
        private async Task Explain(DocumentsOperationContext context, HttpMethod method)
        {
            var indexQuery = await GetIndexQuery(context, method);

            var runner = new QueryRunner(Database, context);

            var explanations = runner.ExplainDynamicIndexSelection(indexQuery);

            using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
            {
                writer.WriteStartObject();
                writer.WriteArray(context, "Results", explanations, (w, c, explanation) =>
                {
                    w.WriteExplanation(context, explanation);
                });
                writer.WriteEndObject();
            }
        }
Exemplo n.º 35
0
        public void NotInArray()
        {
            RequiredDataContainer ModelData = SelectDataProvider.GetData();

            string HandcraftedQuery = Utils.ReadQueryFromFile("HandcraftedQueries/selectNotInArray.js");

            Assert.IsNotNull(HandcraftedQuery);

            MapRule PersonRule = ModelData.ERMongoMapping.Rules.First(R => R.Source.Name == "Person");
            string  AgeMap     = PersonRule.Rules.First(R => R.Key == "age").Value;

            LogicalExpression left = new LogicalExpression($"${AgeMap}", LogicalOperator.NOT_IN,
                                                           new JSArray(new List <object>()
            {
                26, 27, 28, 29
            }));

            SelectArgument Arg      = new SelectArgument(left);
            SelectStage    SelectOp = new SelectStage(Arg, ModelData.ERMongoMapping);

            List <AlgebraOperator> OperatorsToExecute = new List <AlgebraOperator>()
            {
                SelectOp
            };
            FromArgument StartArg = new FromArgument(new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person")),
                                                     ModelData.ERMongoMapping);
            QueryGenerator QueryGen = new QueryGenerator(StartArg, OperatorsToExecute);

            string GeneratedQuery = QueryGen.Run();

            Assert.IsNotNull(GeneratedQuery);

            QueryRunner Runner = new QueryRunner("mongodb://localhost:27017", "select");

            string HandcraftedResult = Runner.GetJSON(HandcraftedQuery);
            string GeneratedResult   = Runner.GetJSON(GeneratedQuery);

            // Check if either result is null
            Assert.IsNotNull(HandcraftedResult);
            Assert.IsNotNull(GeneratedResult);

            // Check if both results are equal
            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(HandcraftedResult), JToken.Parse(GeneratedResult)));
        }
Exemplo n.º 36
0
        public ActionResult ShowSingleSiteCsv(string sitename, int revisionId)
        {
            Query query = QueryUtil.GetQueryForRevision(revisionId);

            if (query == null)
            {
                return(PageNotFound());
            }

            var site = GetSite(sitename);

            if (sitename == null)
            {
                return(PageNotFound());
            }

            var parsedQuery = new ParsedQuery(query.QueryBody, Request.Params);

            if (!parsedQuery.IsExecutionReady)
            {
                return(PageBadRequest());
            }

            CachedResult cachedResults = QueryUtil.GetCachedResults(
                parsedQuery,
                Site.Id
                );
            List <ResultSet> resultSets;

            if (cachedResults != null)
            {
                resultSets = JsonConvert.DeserializeObject <List <ResultSet> >(cachedResults.Results);
            }
            else
            {
                resultSets = QueryRunner.GetResults(
                    parsedQuery,
                    site,
                    CurrentUser
                    ).ResultSets;
            }

            return(new CsvResult(resultSets));
        }
Exemplo n.º 37
0
        public void Equal()
        {
            //RequiredDataContainer ModelData = SelectDataProvider.GetData();
            var ModelData = QueryBuilderParser.ParseMapping(Utils.ReadMappingFile("Mappings/select.mapping"));

            string HandcraftedQuery = Utils.ReadQueryFromFile("HandcraftedQueries/selectEqual.js");

            Assert.IsNotNull(HandcraftedQuery);

            //MapRule PersonRule = ModelData.ERMongoMapping.Rules.First( R => R.Source.Name == "Person" );
            //string AgeMap = PersonRule.Rules.First( R => R.Key == "age" ).Value;
            //LogicalExpression left = new LogicalExpression( $"${AgeMap}", LogicalOperator.EQUAL, 27 );

            //SelectArgument Arg = new SelectArgument( left );
            //SelectStage SelectOp = new SelectStage( Arg, ModelData.ERMongoMapping );

            //List<AlgebraOperator> OperatorsToExecute = new List<AlgebraOperator>() { SelectOp };
            //FromArgument StartArg = new FromArgument( new QueryableEntity( ModelData.EntityRelationshipModel.FindByName( "Person" ) ),
            //    ModelData.ERMongoMapping );
            //QueryGenerator QueryGen = new QueryGenerator( StartArg, OperatorsToExecute );

            string QueryString = "from Person select * where Person.age = 27";
            // FIXME
            // Consulta: from Person where Person.age = 27 select *
            // Problema: Parser não gerou operação de seleção.

            QueryGenerator QueryGen = QueryBuilderParser.ParseQuery(QueryString, ModelData);

            string GeneratedQuery = QueryGen.Run();

            Assert.IsNotNull(GeneratedQuery);

            QueryRunner Runner = new QueryRunner("mongodb://localhost:27017", "select");

            string HandcraftedResult = Runner.GetJSON(HandcraftedQuery);
            string GeneratedResult   = Runner.GetJSON(GeneratedQuery);

            // Check if either result is null
            Assert.IsNotNull(HandcraftedResult);
            Assert.IsNotNull(GeneratedResult);

            // Check if both results are equal
            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(HandcraftedResult), JToken.Parse(GeneratedResult)));
        }
Exemplo n.º 38
0
 internal Notifications(QueryRunner queryRunner)
     : base(queryRunner)
 {
 }
Exemplo n.º 39
0
        public void TruncateDestinationTables()
        {
            var destinationQueryRunner = new QueryRunner(tableSet.DestinationConnectionStringName);
            var destinationQueries = new List<SQLQuery>();

            foreach (var tableMap in tableSet.Mappings.Where(ts=>ts.TruncateDestinationAndBulkLoadFromSource).OrderByDescending(ts => ts.Ordinal))
            {
                Logging.WriteMessageToApplicationLog("About to delete all rows in table " + tableMap.FullyQualifiedDestinationTable, EventLogEntryType.Information);
                var destinationSql = "delete from " + tableMap.FullyQualifiedDestinationTable + ";";
                var destinationQuery = new SQLQuery(destinationSql, SQLQueryType.NonQuery);
                destinationQueries.Add(destinationQuery);
            }
            destinationQueryRunner.RunQuery(destinationQueries, true);
        }
Exemplo n.º 40
0
            // Bereit zum senden von Kommandos
            private void OnReadyToSendCommands(object sender, EventArgs e)
            {
                // Logging
                Logging.Log("Verbindung erfolgreich. Starte Authentifizierung...");

                // Login
                query = new QueryRunner(tcpSocket);
                query.Login(username, password);
                query.SelectVirtualServerByPort(serverPort);
                query.UpdateCurrentQueryClient(new ClientModification() { Nickname = TeamSpeakBot.settings.name } );

                // Mehr Logging
                Logging.Log("Authentifizierung erfolgreich. Starte Bot-Logik...");

                // Bot Logik
                Type[] types = Assembly.GetAssembly(GetType()).GetTypes().Where(t => t.GetInterface("IBotLogic") != null).ToArray();
                foreach (Type bot in types)
                {
                    Logging.Log("Starte " + bot.Name + "...");
                    try
                    {
                        IBotLogic logic = Activator.CreateInstance(bot) as IBotLogic;
                        fetch.botLogic.Add(logic);
                        Logging.LogSpecial(bot.Name + " gestartet.");
                    }
                    catch (Exception e2)
                    {
                        Logging.LogWarning("Kann " + bot.Name + " nicht starten!");
                        Logging.LogException(e2);
                    }
                }

                // Status
                connected = true;
            }
Exemplo n.º 41
0
 public SyncChangesData(TableSet tableSet)
 {
     this.tableSet = tableSet;
     this.SourceDb = new QueryRunner(tableSet.SourceConnectionStringName);
 }