public void CreateSubscription(ServiceBusEnpointData value) {
            //TODO determine how we can change the filters for an existing registered item

            logger.Log(LogLevel.Info, "CreateSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);

            SubscriptionDescription desc = null;

            var data = value.MessageType.FullName;

            if (!namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
                logger.Log(LogLevel.Info, "CreateSubscription Creating {0}", value.SubscriptionName);

                var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                Helpers.Execute(() => {
                    desc = namespaceManager.CreateSubscription(topic.Path, value.SubscriptionName, filter);
                });
            }
            else {
                logger.Log(LogLevel.Info, "CreateSubscription Exists {0}", value.SubscriptionName);
                desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
            }

            SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, ReceiveMode.PeekLock);

            var state = new AzureBusReceiverState() {
                Client = subscriptionClient,
                EndPointData = value,
                Subscription = desc
            };
            mappings.Add(state);

            Task t = new Task(ProcessMessagesForSubscription, state);
            t.Start();
        }
Пример #2
0
        public static Filter GetFilter(AmqpFilter amqpFilter)
        {
            Filter sqlFilter;

            if (amqpFilter.DescriptorCode == AmqpSqlFilter.Code)
            {
                sqlFilter = new SqlFilter(((AmqpSqlFilter)amqpFilter).Expression);
            }
            else if (amqpFilter.DescriptorCode == AmqpTrueFilter.Code)
            {
                sqlFilter = new TrueFilter();
            }
            else if (amqpFilter.DescriptorCode != AmqpFalseFilter.Code)
            {
                if (amqpFilter.DescriptorCode != AmqpCorrelationFilter.Code)
                {
                    throw new NotSupportedException();
                }
                sqlFilter = new CorrelationFilter(((AmqpCorrelationFilter)amqpFilter).CorrelationId);
            }
            else
            {
                sqlFilter = new FalseFilter();
            }
            return(sqlFilter);
        }
Пример #3
0
        static void Main(string[] args)
        {
            // Connect to the Service Bus namespace using a SAS Url with the Manage permission
            _nameSpaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);

            // Create the topic if it does not already exist
            if (!_nameSpaceManager.TopicExists(_topicName))
            {
                _nameSpaceManager.CreateTopic(_topicName);
            }

            // Create a new subscription with a message filter to only accept
            // messages from the ServiceBusSender - to be used by the ServiceBusSubscriber web application
            SqlFilter externalSubscriptionFilter = new SqlFilter("From = 'ServiceBusSender'");

            if (!_nameSpaceManager.SubscriptionExists(_topicName, _externalSubscriptionName))
            {
                _nameSpaceManager.CreateSubscription(_topicName, _externalSubscriptionName, externalSubscriptionFilter);
            }

            // Create a new subscription with a message filter to only accept
            // response messages from the ServiceBusSubscriber - to be used by the Azure Function subscriber
            SqlFilter functionSubscriptionFilter = new SqlFilter("From = 'ServiceBusSubscriber'");

            if (!_nameSpaceManager.SubscriptionExists(_topicName, _functionSubscriptionName))
            {
                _nameSpaceManager.CreateSubscription(_topicName, _functionSubscriptionName, functionSubscriptionFilter);
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            // Connect to the Service Bus namespace using a SAS Url with the Manage permission
            _nameSpaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);

            // Create the topic if it does not already exist
            if (!_nameSpaceManager.TopicExists(_topicName))
            {
                _nameSpaceManager.CreateTopic(_topicName);
            }

            // Create a new subscription with a message filter to only accept
            // messages from the ServiceBusSender - to be used by the ServiceBusSubscriber web application
            SqlFilter subscriptionFilter = new SqlFilter("Customer = 'Customer1'");

            if (!_nameSpaceManager.SubscriptionExists(_topicName, _subscriptionName))
            {
                _nameSpaceManager.CreateSubscription(_topicName, _subscriptionName, subscriptionFilter);
            }

            Console.WriteLine($"**** {_subscriptionName} has started ***");
            Task.Run(() => ProcessMessages());
            Console.WriteLine($"*** {_subscriptionName} is Running. Press any key to stop. ***");
            Console.Read();
            Console.WriteLine($"*** {_subscriptionName} is Stopping ***");
            _isStopped = true;
        }
        private SubscriptionClient CreateAndGetSubscriptionInternal(string subscriptionName, ISpecification filterSpecification)
        {
            var filter = new SqlFilter(filterSpecification.Result());
            EnsureSubscriptionNameIsValid(subscriptionName);

            log.Info($"Checking subscription for path {subscriptionName} exists");

            if (!this.namespaceManager.SubscriptionExists(this.topic, subscriptionName))
            {
                log.Info("Creating subscription as it does not currently exist");

                var subscriptionDescription = new SubscriptionDescription(this.topic, subscriptionName)
                {
                    LockDuration = TimeSpan.FromMinutes(5)
                };

                this.namespaceManager.CreateSubscription(subscriptionDescription, filter);

                log.Info("Subscription created");
            }

            log.Info("Creating subscription client");

            var client = SubscriptionClient.CreateFromConnectionString(
                connectionString, this.topic, subscriptionName);

            log.Info("Subscription client created");

            return client;
        }
Пример #6
0
        private string BuildSqlFrom(FranchiseeFilter filter)
        {
            if (filter == null)
            {
                return(null);
            }

            var sb = new System.Text.StringBuilder();

            if (!string.IsNullOrEmpty(filter.Email))
            {
                sb.Append(" email like '%" + SqlFilter.FilterQueryParameter(filter.Email) + "%' ");
                sb.Append(" and ");
            }

            if (!string.IsNullOrEmpty(filter.Name))
            {
                sb.Append(" name like '%" + SqlFilter.FilterQueryParameter(filter.Name) + "%' ");
                sb.Append(" and ");
            }
            if (!string.IsNullOrEmpty(filter.Phone))
            {
                sb.Append(" phone like '%" + SqlFilter.FilterQueryParameter(filter.Phone) + "%' ");
                sb.Append(" and ");
            }

            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 4, 4);
            }

            return(sb.ToString());
        }
Пример #7
0
        public static AmqpFilter GetFilter(Filter filter)
        {
            AmqpFilter amqpTrueFilter = null;

            if (filter is TrueFilter)
            {
                amqpTrueFilter = new AmqpTrueFilter();
            }
            else if (filter is FalseFilter)
            {
                amqpTrueFilter = new AmqpFalseFilter();
            }
            else if (!(filter is SqlFilter))
            {
                if (!(filter is CorrelationFilter))
                {
                    throw new NotSupportedException();
                }
                amqpTrueFilter = new AmqpCorrelationFilter()
                {
                    CorrelationId = ((CorrelationFilter)filter).CorrelationId
                };
            }
            else
            {
                AmqpSqlFilter amqpSqlFilter = new AmqpSqlFilter();
                SqlFilter     sqlFilter     = (SqlFilter)filter;
                amqpSqlFilter.Expression         = sqlFilter.SqlExpression;
                amqpSqlFilter.CompatibilityLevel = new int?(sqlFilter.CompatibilityLevel);
                amqpTrueFilter = amqpSqlFilter;
            }
            return(amqpTrueFilter);
        }
Пример #8
0
        /// <summary>
        /// Subscribes to a stream of messages that match a .NET type.
        /// </summary>
        /// <typeparam name="T">The type to subscribe to</typeparam>
        /// <param name="onMessage">The action to run when a message arrives.</param>
        /// <param name="configure">The configure action.</param>
        public void Subscribe <T>(Action <T> onMessage, Action <ISubscriptionConfiguration> configure) where T : class
        {
            Type messageType = typeof(T);

            ISubscriptionConfiguration configuration = this.Configuration.SubscriptionConfiguration();

            configure(configuration);

            string topic = this.CreateTopicIfNotExists <T>(configuration);

            string realSubscriptionId = configuration.Subscription.ToLowerInvariant();

            if (!this.namespaceManager.SubscriptionExists(topic, realSubscriptionId))
            {
                SqlFilter filter = new SqlFilter(string.Format("[Message.Type.FullName] = '{0}'", messageType.FullName));
                SubscriptionDescription dataCollectionTopic = this.namespaceManager.CreateSubscription(topic, realSubscriptionId, filter);
            }

            string             descriptor = topic + ":" + realSubscriptionId;
            SubscriptionClient client     = this.subscriptionClients.GetOrAdd(
                descriptor,
                (d) =>
            {
                return(SubscriptionClient.CreateFromConnectionString(
                           this.Configuration.ConnectionString,
                           topic,
                           realSubscriptionId,
                           configuration.ReceiveMode));
            });

            OnMessageOptions options = new OnMessageOptions()
            {
                AutoComplete       = false,
                MaxConcurrentCalls = configuration.MaxConcurrentCalls
            };


            client.OnMessage(envelope =>
            {
                try
                {
                    this.Configuration.Logger.InfoFormat(
                        "Message was received on Subscription {0} Topic {1} with MessageId {2}",
                        realSubscriptionId,
                        topic,
                        envelope.MessageId);

                    object message = JsonConvert.DeserializeObject(envelope.GetBody <string>(), messageType);
                    onMessage(message as T);
                    envelope.Complete();
                }
                catch (Exception ex)
                {
                    this.Configuration.Logger.Fatal(ex);
                    envelope.Abandon();
                }
            },
                             options);
        }
Пример #9
0
        public void Select_EqualsExpected()
        {
            var table = new SqlTable <Class1>();

            var order = new
            {
                Id = new OrderItem {
                    Direction = OrderDirection.Asc, Index = 2
                },
                Value1 = new OrderItem {
                    Direction = OrderDirection.Desc, Index = 1
                },
                DoNotChange = (OrderItem)null
            };
            var orderMap  = OrderMap.FromOrder(table, order);
            var sqlFilter = SqlFilter.Construct(
                new { Ids = new[] { 1, 2 }, Value1 = "foo", Auto = (int?)null }
                );

            var whereSql = new[]
            {
                Conditions.Or(sqlFilter[f => f.Ids].IsNull(), table[m => m.Id].EqualsAny(sqlFilter[f => f.Ids])),
                Conditions.Or(sqlFilter[f => f.Value1].IsNull(),
                              table[m => m.Value1].EqualsOne(sqlFilter[f => f.Value1]))
            };
            var sqlOptions = new SqlOptions {
                Dialect = SqlDialect.Postgres95
            };
            var sqlBuilder = SqlBuilder.Select
                             .Values(table)
                             .From(table)
                             .Where(whereSql)
                             .Order(orderMap)
                             .Offset(5)
                             .LimitBy(10);


            var actual   = sqlBuilder.BuildSql(sqlOptions);
            var expected = @"
            SELECT
              class1.id AS Id,
              class1.auto AS Auto,
              class1.value1 AS Value1,
              class1.value2 AS Value2,
              class1.do_not_change AS DoNotChange
            FROM foo.class1
            WHERE
                   (@Ids IS NULL OR class1.id = ANY(@Ids))
               AND (@Value1 IS NULL OR class1.value1 = @Value1)
            ORDER BY
              class1.value1 DESC,
              class1.id ASC
            OFFSET 5
            LIMIT 10
            ";

            Check(expected, actual);
            Assert.AreEqual("Id", sqlBuilder.SplitOn);
        }
Пример #10
0
        public void Or_SqlFilterBase_Success()
        {
            var filter = SqlFilter <Person> .From(m => m.Id).EqualTo(5);

            var filter2 = SqlFilter <Passport> .From(m => m.Id).EqualTo(6);

            Assert.Equal("pe.Id = 5 OR pa.Id = 6", SqlFilter <Passport> .Empty.And(filter).Or(filter2).RawSql);
        }
Пример #11
0
        public void AndGroup_SqlFilterBase_Success()
        {
            var filter = SqlFilter <Person> .From(m => m.Id).EqualTo(5);

            var filter2 = SqlFilter <Passport> .From(m => m.Id).EqualTo(6);

            Assert.Equal("pe.Id = 5 AND (pa.Id = 6)", SqlFilter <Passport> .Empty.And(filter).AndGroup(filter2).RawSql);
        }
Пример #12
0
 internal ServiceBusRuleData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, FilterAction action, FilterType?filterType, SqlFilter sqlFilter, CorrelationFilter correlationFilter) : base(id, name, type)
 {
     SystemData        = systemData;
     Action            = action;
     FilterType        = filterType;
     SqlFilter         = sqlFilter;
     CorrelationFilter = correlationFilter;
 }
Пример #13
0
 /// <summary>
 /// Gets all entities.
 /// </summary>
 /// <returns></returns>
 public override IList GetAll()
 {
     if (EntityType == null)
     {
         throw new InvalidOperationException("EntityType is null.");
     }
     return(SqlFilter.GetAll(this.EntityType));
 }
Пример #14
0
        public void And_SqlFilterBase_Success()
        {
            var filter = SqlFilter <Person> .From(m => m.Id).EqualTo(5);

            var filter2 = SqlFilter <Passport> .From(m => m.Id).EqualTo(6);

            Assert.Equal("pe.Id = 5 AND pa.Id = 6", filter.And(filter2).RawSql);
        }
Пример #15
0
        public void OrGroup_SqlFilterBase_Success()
        {
            var filter = SqlFilter <Person> .From(m => m.Id).EqualTo(5);

            var filter2 = SqlFilter <Passport> .From(m => m.Id).EqualTo(6);

            Assert.Equal("pe.Id = 5 OR (pa.Id = 6)", filter.OrGroup(filter2).RawSql);
        }
Пример #16
0
            public void TestMethod_In2()
            {
                var str      = "2, 6, 7";
                var expected = "A IN (2,6,7)";
                var actual   = DbHelper.GetWhereString(SqlFilter.In("A", 2, 6, 7)); //   Array.ForEach(array, i => )

                Assert.AreEqual(expected, actual);
            }
Пример #17
0
            public void TestMethod_Gt()
            {
                var expected = "6 > 5 AND 11 > 10 AND 8 > 7";
                var actual   =
                    DbHelper.GetWhereString(SqlFilter.Gt("6", 5), SqlFilter.Gt("11", 10), SqlFilter.Gt("8", 7));

                Assert.AreEqual(expected, actual);
            }
Пример #18
0
        public void And_WithoutAliases_Success()
        {
            var filter = SqlFilter <Person> .From(m => m.Id).EqualTo(5)
                         .And(m => m.Name).EqualTo("Sergey");

            Assert.Equal("Id = 5 AND Name = 'Sergey'", filter.WithoutAliases().RawSql);
            Assert.Equal("pe.Id = 5 AND pe.Name = 'Sergey'", filter.RawSql);
        }
        static void Main()
        {
            //Build the Service Bus connection string (again, not necessary if using config from the config file)
            var connBuilder = new ServiceBusConnectionStringBuilder();

            connBuilder.ManagementPort = HttpPort;
            connBuilder.RuntimePort    = TcpPort;
            connBuilder.Endpoints.Add(new UriBuilder {
                Scheme = "sb", Host = ServerFqdn, Path = ServiceNamespace
            }.Uri);
            connBuilder.StsEndpoints.Add(new UriBuilder {
                Scheme = "https", Host = ServerFqdn, Port = HttpPort, Path = ServiceNamespace
            }.Uri);


            var messageFactory   = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

            const string topicName = "DemoTopic";
            //const string subscriptionName = "status_verifications";
            const string subscriptionName = "Subscription1";

            //Give the publisher some time to create the topic
            System.Threading.Thread.Sleep(5000);

            //Only uncomment to reset the subscription
            //namespaceManager.DeleteSubscription(topicName, subscriptionName);


            //Create the subscription (if it doesn't exist)
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName))
            {
                //Only subscribe to messages that are Type1
                var filter = new SqlFilter("Type = 'Type1'");

                namespaceManager.CreateSubscription(topicName, subscriptionName, filter);
            }


            // Create the subscription client
            var subscriptionClient = messageFactory.CreateSubscriptionClient(topicName, subscriptionName, ReceiveMode.PeekLock);

            Console.WriteLine(subscriptionName);
            Console.WriteLine("----------------");

            while (true)
            {
                var message = subscriptionClient.Receive(TimeSpan.FromSeconds(5));
                if (message != null)
                {
                    Console.WriteLine("{0} message received: Id = {1}; delivery count = {2}",
                                      subscriptionName, message.MessageId, message.DeliveryCount);
                    message.Abandon();
                }

                System.Threading.Thread.Sleep(10);
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            string topicName = "sb-salesorder-topic";
            string sbconnection = "Endpoint=sb://sb-twocents-ns.servicebus.windows.net/;SharedAccessKeyName=Admin;SharedAccessKey=mueFV8NQkt5MmSIMzbbXvBw4EAtXLntue/gLP7OfSEE=";
            var ns = NamespaceManager.CreateFromConnectionString(sbconnection);
            SqlFilter filter = new SqlFilter("Priority=1");
            ns.CreateSubscription(topicName, "salesorder-sub-priority", filter);

        }
Пример #21
0
        static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter)
        {
            var amqpFilterMap = new AmqpMap
            {
                [ManagementConstants.Properties.Expression] = sqlFilter.SqlExpression
            };

            return(amqpFilterMap);
        }
Пример #22
0
        /// <summary>
        /// Finds a MailMessage entity using it's primary key.
        /// </summary>
        /// <param name="MailMessageId">A key field.</param>
        /// <returns>A MailMessage object.</returns>
        /// <exception cref="Spring2.Core.DAO.FinderException">Thrown when no entity exists witht he specified primary key..</exception>
        public MailMessage Load(IdType mailMessageId)
        {
            SqlFilter filter = new SqlFilter();

            filter.And(new SqlEqualityPredicate("MailMessageId", EqualityOperatorEnum.Equal, mailMessageId.IsValid ? mailMessageId.ToInt32() as Object : DBNull.Value));
            IDataReader dataReader = GetListReader(CONNECTION_STRING_KEY, VIEW, filter, null);

            return(GetDataObject(dataReader));
        }
Пример #23
0
            public void SqlFilterTests_Or()
            {
                var expected = "A=5 OR B=6 OR C=3";
                var actual   =
                    DbHelper.GetWhereString(SqlFilter.Eq("A", 5).Or(SqlFilter.Eq("B", 6)).Or(SqlFilter.Eq("C", 3)));

                Assert.AreEqual(expected, actual);
                ;
            }
Пример #24
0
        public async Task <IReadOnlyCollection <T> > FindUnversionedContent <T>(SqlFilter condition) where T : UnversionedContentEntity, new()
        {
            var joinedCondition = condition.Filter;

            //todo : not secure
            joinedCondition = NoParameterizationTerribleHack(condition, joinedCondition);

            return(await Task.FromResult(FindContentImpl <T>(joinedCondition)));
        }
 private bool ValidateParameters()
 {
     try
     {
         int temp;
         if (string.IsNullOrEmpty(txtReceiveTimeout.Text) ||
             !int.TryParse(txtReceiveTimeout.Text, out temp) ||
             temp < 0)
         {
             writeToLog(ReceiveTimeoutCannotBeNull);
             return(false);
         }
         receiveTimeout = temp;
         if (string.IsNullOrEmpty(txtSessionTimeout.Text) ||
             !int.TryParse(txtSessionTimeout.Text, out temp) ||
             temp < 0)
         {
             writeToLog(SessionTimeoutCannotBeNull);
             return(false);
         }
         sessionTimeout = temp;
         if (string.IsNullOrEmpty(txtPrefetchCount.Text) ||
             !int.TryParse(txtPrefetchCount.Text, out temp))
         {
             writeToLog(PrefetchCountCannotBeNull);
             return(false);
         }
         prefetchCount = temp;
         if (!int.TryParse(txtReceiveBatchSize.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiverBatchSizeMustBeANumber);
             return(false);
         }
         receiverBatchSize = temp;
         if (!int.TryParse(txtReceiveTaskCount.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiveTaskCountMustBeANumber);
             return(false);
         }
         receiverTaskCount = temp;
         var sqlFilter = new SqlFilter(!string.IsNullOrEmpty(txtFilterExpression.Text)
                                                           ? txtFilterExpression.Text
                                                           : DefaultFilterExpression);
         sqlFilter.Validate();
         filter = sqlFilter.Preprocess();
         if (filter == null)
         {
             writeToLog(FilterExpressionIsNotValid);
         }
     }
     catch (Exception ex)
     {
         HandleException(ex);
         return(false);
     }
     return(true);
 }
        public ActionResult Index()
        {
            //create containers
            var acct                 = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]);
            var client               = acct.CreateCloudBlobClient();
            var uploadContainer      = client.GetContainerReference("upload");
            var uploadThumbContainer = client.GetContainerReference("uploadthumb");

            uploadContainer.CreateIfNotExists();
            uploadContainer.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
            uploadThumbContainer.CreateIfNotExists();
            uploadThumbContainer.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
            var savedContainer      = client.GetContainerReference("saved");
            var savedThumbContainer = client.GetContainerReference("savedthumb");

            savedContainer.CreateIfNotExists();
            savedContainer.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
            savedThumbContainer.CreateIfNotExists();
            savedThumbContainer.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            //create queue, topic and subs
            //subs need to be recreated because functions create them without filters
            var nsm = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["ServiceBusConnection"]);

            if (!nsm.QueueExists("resize"))
            {
                nsm.CreateQueue("resize");
            }
            if (!nsm.TopicExists("process"))
            {
                nsm.CreateTopic("process");
            }
            if (nsm.SubscriptionExists("process", "save"))
            {
                nsm.DeleteSubscription("process", "save");
            }
            var saveFilter = new SqlFilter("Action = 0");

            nsm.CreateSubscription("process", "save", saveFilter);
            if (nsm.SubscriptionExists("process", "delete"))
            {
                nsm.DeleteSubscription("process", "delete");
            }
            var deleteFilter = new SqlFilter("Action = 1");

            nsm.CreateSubscription("process", "delete", deleteFilter);

            return(View());
        }
Пример #27
0
        public List <T> GetItems(SqlFilter filter)
        {
            string sql = BuildSelectSql(filter);

            //KeyValuePair<string, object>[] arrayParameter = Parameters.ToArray();

            //build couchbase key
            //string[] strParms = Parameters.Values.Select(p => {
            //    if (p.SqlDbType == SqlDbType.Int)
            //        return p.ParameterName + "=" + p.SqlValue.ToString();
            //    else
            //        return p.ParameterName + "=\"" + p.SqlValue.ToString()+"\"";
            //}).ToArray();


            //string key = !string.IsNullOrEmpty(filter.Identiy) ? filter.Identiy : typeof(T).Name + "_" + MD5Class.GetMD5ValueUTF8(sql) + "_" + string.Join(",", strParms);

            //CouchbaseClient client = CouchbaseHelper.CreateInstance();

            //if (filter.ForceRefresh || (!string.IsNullOrEmpty(RequestContext.Current.request["reloadcache"]) && RequestContext.Current.request["reloadcache"] == "1"))
            //{
            //    client.Remove(key);
            //}



            //if (!string.IsNullOrEmpty(filter.CacheKey))
            //    key = filter.CacheKey;

            //if (client.KeyExists(key))
            //    list = client.Get<List<T>>(key);
            //else

            CouchbaseHelper helper = new CouchbaseHelper("default");
            List <T>        list   = helper.Query <T>(sql, Parameters);



            //if (list != null)
            //{
            //    foreach (T to in list)
            //    {
            //        LateBind(filter.Binds, to);
            //    }

            //    if (filter.CacheLevel >0)
            //    {

            //        client.Store(StoreMode.Set, key, list, TransCacheLevel(filter.CacheLevel));
            //    }
            //}



            return(list);
        }
Пример #28
0
 /// <summary>
 /// This is a shared function that can be used to delete records using a where clause.
 /// </summary>
 public static void DeleteRecords(string where)
 {
     if (where == null || where.Trim() == "")
     {
        return;
     }
     
     SqlFilter whereFilter = new SqlFilter(where);
     PhotoClubsTable.Instance.DeleteRecordList(whereFilter);
 }
Пример #29
0
        /// <summary>
        /// Returns a list of objects which match the values for the fields specified.
        /// </summary>
        /// <param name="MailMessageStatus">A field value to be matched.</param>
        /// <returns>The list of MailMessageDAO objects found.</returns>
        public MailMessageList FindByStatus(MailMessageStatusEnum mailMessageStatus)
        {
            OrderByClause sort   = new OrderByClause("MailMessageStatus");
            SqlFilter     filter = new SqlFilter();

            filter.And(new SqlEqualityPredicate("MailMessageStatus", EqualityOperatorEnum.Equal, mailMessageStatus.DBValue));
            IDataReader dataReader = GetListReader(CONNECTION_STRING_KEY, VIEW, filter, null);

            return(GetList(dataReader));
        }
Пример #30
0
 /// <summary>
 /// This is a shared function that can be used to export records using a where clause.
 /// </summary>
 public static string Export(string where)
 {
     SqlFilter whereFilter = null;
     if (where != null && where.Trim() != "")
     {
        whereFilter = new SqlFilter(where);
     }
     
     return  PhotoClubsTable.Instance.ExportRecordData(whereFilter);
 }
Пример #31
0
 public void ApplySqlFilter(DbContentClip clip)
 {
     clip.Title         = SqlFilter.FilterString(clip.Title, 255);
     clip.Subtitle      = SqlFilter.FilterString(clip.Subtitle, 255);
     clip.ContentString = SqlFilter.FilterString(clip.ContentString);
     for (int x = 0; x <= clip.keywords.GetUpperBound(0); x++)
     {
         clip.keywords[x] = SqlFilter.FilterString(clip.keywords[x]);
     }
 }
Пример #32
0
        public void InnerJoin()
        {
            var alias    = new SqlAlias <Passport>("pas");
            var expected =
                @"INNER JOIN
    Passport pas ON pas.PersonId = pe.Id";

            Assert.Equal(expected, new SqlJoin <Passport>(JoinType.Inner,
                                                          SqlFilter <Passport> .From(p => p.PersonId, alias).EqualTo <Person>(p => p.Id), alias).ToString());
        }
Пример #33
0
        public void FullJoin()
        {
            var alias    = new SqlAlias <Passport>("pas");
            var expected =
                @"FULL JOIN
    Passport pas ON pe.Id = pas.PersonId";

            Assert.Equal(expected, new SqlJoin <Passport>(JoinType.Full,
                                                          SqlFilter <Person> .From(p => p.Id).EqualTo <Passport>(p => p.PersonId, alias), alias).ToString());
        }
        public void PreExecute(SqlFilter filter)
        {
            if (filter == null)
                throw new ArgumentNullException("filter");

            // get...
            UserItem user = ServiceAuthenticator.Current.GetUser();
            if (user == null)
                throw new InvalidOperationException("'user' is null.");

            // mangle the query...
            filter.Constraints.Add("userid", user.UserId);
        }
Пример #35
0
        /// <summary>
        /// Cancel a subscription
        /// </summary>
        /// <param name="value">The data used to cancel the subscription</param>
        public void CancelSubscription(ServiceBusEnpointData value)
        {
            Guard.ArgumentNotNull(value, "value");
            var subscription = mappings.FirstOrDefault(item => item.Data.EndPointData.SubscriptionName.Equals(value.SubscriptionName, StringComparison.OrdinalIgnoreCase));

            if (subscription == null)
            {
                return;
            }

            subscription.Data.Cancel();

            Task t = Task.Factory.StartNew(() =>
            {
                //HACK find better way to wait for a cancel request so we are not blocking.
                for (int i = 0; i < 100; i++)
                {
                    if (!subscription.Data.Cancelled)
                    {
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        break;
                    }
                }

                if (configurationFactory.NamespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName))
                {
                    var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                    retryPolicy.ExecuteAction(() => configurationFactory.NamespaceManager.DeleteSubscription(topic.Path, value.SubscriptionName));
                }
            });

            try
            {
                Task.WaitAny(t);
            }
            catch (Exception ex)
            {
                if (ex is AggregateException)
                {
                    //do nothing
                }
                else
                {
                    throw;
                }
            }
        }
Пример #36
0
        static void Main(string[] args)
        {
            string connectionStr = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            NamespaceManager nsm = NamespaceManager.CreateFromConnectionString(connectionStr);
            string topicName = "yolitopic";
            TopicDescription topic = null;
            if (!nsm.TopicExists(topicName))
            {
                nsm.CreateTopic(new TopicDescription(topicName) { 
                    EnablePartitioning = false
                });
            }

            topic = nsm.GetTopic(topicName);

            if (topic.SubscriptionCount == 0)
            {
                SqlFilter filter1 = new SqlFilter("(index % 2) = 0");
                nsm.CreateSubscription(topic.Path, "YoliSubscription1", filter1);
                SqlFilter filter2 = new SqlFilter("(index % 2) > 0");
                nsm.CreateSubscription(topic.Path, "YoliSubscription2", filter2);
            }
            //
            //sadfsdf

            foreach(var s in nsm.GetSubscriptions(topicName))
            {
                Console.WriteLine(s.Name);
                foreach(var r in nsm.GetRules(topic.Path,s.Name))
                {
                    Console.WriteLine("{0}-{1}", r.Name, r.Filter.ToString());
                }
            }

            Console.WriteLine("Sending message to topic");

            TopicClient topicClient = TopicClient.CreateFromConnectionString(connectionStr, topicName);
            for (int i = 0; i < 5000; i++)
            {
                BrokeredMessage message = new BrokeredMessage();
                message.Properties["index"] = i;
                message.Properties["value"] = (i * 10 + 5) % 11;
                topicClient.Send(message);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Пример #37
0
        private async Task EnsureTopic()
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(_globalSettings.ServiceBusConnectionString);

            if (await namespaceManager.TopicExistsAsync(_globalSettings.DiscoTopicName) == false)
            {
                await namespaceManager.CreateTopicAsync(_globalSettings.DiscoTopicName);
            }
            if (await namespaceManager.SubscriptionExistsAsync(_globalSettings.DiscoTopicName, "Gadgets") == false)
            {
                var discoFilter = new SqlFilter("Disco = true");
                await namespaceManager.CreateSubscriptionAsync(_globalSettings.DiscoTopicName, "Gadgets", discoFilter);
            }
            if (await namespaceManager.SubscriptionExistsAsync(_globalSettings.DiscoTopicName, "Notifications") == false)
            {
                await namespaceManager.CreateSubscriptionAsync(_globalSettings.DiscoTopicName, "Notifications");
            }
        }
        public static SubscriptionDescription GetOrCreateSubscription(this NamespaceManager namespaceManager, TopicDescription topicDescription,
                                                                      string name)
        {
            if (!namespaceManager.SubscriptionExists(topicDescription.Path, name))
            {
                try
                {
                    var filter = new SqlFilter(string.Format("LogicalDestinationQueue = '{0}'", name));
                    var subscription = namespaceManager.CreateSubscription(topicDescription.Path, name, filter);
                    return subscription;
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                }
            }

            return namespaceManager.GetSubscription(topicDescription.Path, name);
        }
        public void MakeSubscription()
        {
            //https://msdn.microsoft.com/en-us/library/azure/hh367516.aspx
            //http://azure.microsoft.com/EN-US/documentation/articles/service-bus-dotnet-how-to-use-topics-subscriptions/

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.SubscriptionExists("WebsiteMessages", "Problem"))
            {
                SqlFilter filter = new SqlFilter("FormType = 'Problem'");
                namespaceManager.CreateSubscription("WebsiteMessages", "Problem", filter);
            }

            if (!namespaceManager.SubscriptionExists("WebsiteMessages", "Question"))
            {
                SqlFilter filter = new SqlFilter("FormType = 'Question'");
                namespaceManager.CreateSubscription("WebsiteMessages", "Question", filter);
            }
        }
Пример #40
0
        private static void Main(string[] args)
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            // Create topic
            if (!namespaceManager.TopicExists(_topicName))
            {
                namespaceManager.CreateTopic(_topicName);
            }

            // Create subscriptions
            if (!namespaceManager.SubscriptionExists(_topicName, "Bookings"))
            {
                SqlFilter filter = new SqlFilter("EventType = 'Booking'");
                namespaceManager.CreateSubscription(_topicName, "Bookings", filter);
            }
            if (!namespaceManager.SubscriptionExists(_topicName, "Notifications"))
            {
                SqlFilter filter = new SqlFilter("EventType = 'Notification'");
                namespaceManager.CreateSubscription(_topicName, "Notifications", filter);
            }

            // Push messages to topics
            TopicClient client = TopicClient.CreateFromConnectionString(connectionString, _topicName);

            int count = 1;
            while (true)
            {
                Task.Run(() => SendMessage(client, "Booking", count));
                Task.Run(() => SendMessage(client, "Notification", count));
                Thread.Sleep(2000);

                count++;
                if (count > 20) break;
            }
        }
        public SubscriptionClient Create(Type eventType, string topicPath, string subscriptionname)
        {
            if (NamespaceClient.TopicExists(topicPath))
            {
                try
                {
                    if (!NamespaceClient.SubscriptionExists(topicPath, subscriptionname))
                    {
                        var description = new SubscriptionDescription(topicPath, subscriptionname)
                            {
                                LockDuration = LockDuration,
                                RequiresSession = RequiresSession,
                                DefaultMessageTimeToLive = DefaultMessageTimeToLive,
                                EnableDeadLetteringOnMessageExpiration = EnableDeadLetteringOnMessageExpiration,
                                MaxDeliveryCount = MaxDeliveryCount,
                                EnableBatchedOperations = EnableBatchedOperations,
                                EnableDeadLetteringOnFilterEvaluationExceptions =
                                    EnableDeadLetteringOnFilterEvaluationExceptions
                            };

                        var filter = string.Format( "[{0}] LIKE '{1}%' OR [{0}] LIKE '%{1}%' OR [{0}] LIKE '%{1}' OR [{0}] = '{1}'", Headers.EnclosedMessageTypes, eventType.AssemblyQualifiedName);
                        var typefilter = new SqlFilter(filter);

                        NamespaceClient.CreateSubscription(description, typefilter);

                    }
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // the queue already exists or another node beat us to it, which is ok
                }

                return Factory.CreateSubscriptionClient(topicPath, subscriptionname, ReceiveMode.PeekLock);
               
            }
            return null;
        }
        public void CancelSubscription(ServiceBusEnpointData value) {

            logger.Log(LogLevel.Info, "CancelSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);

            var subscription = mappings.FirstOrDefault(item => item.EndPointData.SubscriptionName.Equals(value.SubscriptionName, StringComparison.OrdinalIgnoreCase));

            if (subscription == null) {
                logger.Log(LogLevel.Info, "CancelSubscription Does not exist {0}", value.SubscriptionName);
                return;
            }

            subscription.Cancel = true;

            Task t = new Task(() => {
                //HACK find better way to wait for a cancel request so we are not blocking.
                logger.Log(LogLevel.Info, "CancelSubscription Deleting {0}", value.SubscriptionName);
                for (int i = 0; i < 100; i++) {
                    if (!subscription.Cancelled) {
                        Thread.Sleep(3000);
                    }
                    else {
                        break;
                    }
                }

                if (namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
                    var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                    Helpers.Execute(() => {
                        namespaceManager.DeleteSubscription(topic.Path, value.SubscriptionName);
                    });
                    logger.Log(LogLevel.Info, "CancelSubscription Deleted {0}", value.SubscriptionName);
                }
            });
            t.Start();
        }
 private void pictFindDeadletter_Click(object sender, EventArgs e)
 {
     try
     {
         deadletterDataGridView.SuspendDrawing();
         deadletterDataGridView.SuspendLayout();
         if (deadletterBindingList == null)
         {
             return;
         }
         using (var form = new TextForm(FilterExpressionTitle, FilterExpressionLabel, deadletterFilterExpression))
         {
             form.Size = new Size(600, 200);
             if (form.ShowDialog() != DialogResult.OK)
             {
                 return;
             }
             deadletterFilterExpression = form.Content;
             if (string.IsNullOrWhiteSpace(deadletterFilterExpression))
             {
                 deadletterBindingSource.DataSource = deadletterBindingList;
                 deadletterDataGridView.DataSource = deadletterBindingSource;
                 writeToLog(FilterExpressionRemovedMessage);
             }
             else
             {
                 Filter filter;
                 try
                 {
                     var sqlFilter = new SqlFilter(deadletterFilterExpression);
                     sqlFilter.Validate();
                     filter = sqlFilter.Preprocess();
                 }
                 catch (Exception ex)
                 {
                     writeToLog(string.Format(FilterExpressionNotValidMessage, deadletterFilterExpression, ex.Message));
                     return;
                 }
                 var filteredList = deadletterBindingList.Where(filter.Match).ToList();
                 var bindingList = new SortableBindingList<BrokeredMessage>(filteredList)
                 {
                     AllowEdit = false,
                     AllowNew = false,
                     AllowRemove = false
                 };
                 deadletterBindingSource.DataSource = bindingList;
                 deadletterDataGridView.DataSource = deadletterBindingSource;
                 writeToLog(string.Format(FilterExpressionAppliedMessage, deadletterFilterExpression, bindingList.Count));
             }
         }
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
     finally
     {
         deadletterDataGridView.ResumeLayout();
         deadletterDataGridView.ResumeDrawing();
     }
 }
Пример #44
0
        /// <summary>
        /// This is a shared function that can be used to get an array of UsersRecord records using a where and order by clause clause with pagination.
        /// </summary>
        public static UsersRecord[] GetRecords(BaseFilter join, string where, OrderBy orderBy, int pageIndex, int pageSize)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }

            ArrayList recList = UsersTable.Instance.GetRecordList(join, whereFilter, null, orderBy, pageIndex, pageSize);

            return (UsersRecord[])recList.ToArray(Type.GetType("FPCEstimate.Business.UsersRecord"));
        }
Пример #45
0
        /// <summary>
        /// This is a shared function that can be used to get a EstimateRecord record using a where and order by clause.
        /// </summary>
        public static EstimateRecord GetRecord(string where, OrderBy orderBy)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }
            BaseClasses.Data.BaseFilter join = null;
            ArrayList recList = EstimateTable.Instance.GetRecordList(join, whereFilter, null, orderBy, BaseTable.MIN_PAGE_NUMBER, BaseTable.MIN_BATCH_SIZE);

            EstimateRecord rec = null;
            if (recList.Count > 0)
            {
            rec = (EstimateRecord)recList[0];
            }

            return rec;
        }
Пример #46
0
        /// <summary>
        /// This is a shared function that can be used to get a UsersRecord record using a where and order by clause.
        /// </summary>
        public static UsersRecord GetRecord(BaseFilter join, string where, OrderBy orderBy)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }

            ArrayList recList = UsersTable.Instance.GetRecordList(join, whereFilter, null, orderBy, BaseTable.MIN_PAGE_NUMBER, BaseTable.MIN_BATCH_SIZE);

            UsersRecord rec = null;
            if (recList.Count > 0)
            {
            rec = (UsersRecord)recList[0];
            }

            return rec;
        }
Пример #47
0
        /// <summary>
        /// This is a shared function that can be used to get total number of records that will be returned using the where clause.
        /// </summary>
        public static int GetRecordCount(BaseFilter join, string where)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }

            return (int)UsersTable.Instance.GetRecordListCount(join, whereFilter, null, null);
        }
Пример #48
0
        /// <summary>
        /// This is a shared function that can be used to delete records using a where clause.
        /// </summary>
        public static void DeleteRecords(string where)
        {
            if (where == null || where.Trim() == "")
            {
               return;
            }

            SqlFilter whereFilter = new SqlFilter(where);
            UsersTable.Instance.DeleteRecordList(whereFilter);
        }
Пример #49
0
        /// <summary>
        /// This is a shared function that can be used to export records using a where clause.
        /// </summary>
        public static string Export(string where)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }

            return  UsersTable.Instance.ExportRecordData(whereFilter);
        }
Пример #50
0
        /// <summary>
        /// This is a shared function that can be used to get total number of records that will be returned using the where clause.
        /// </summary>
        public static int GetRecordCount(string where)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }

            return (int)EstimateTable.Instance.GetRecordListCount(null, whereFilter, null, null);
        }
        public void CreateSubscription(ServiceBusEnpointData value) {
            Guard.ArgumentNotNull(value, "value");

            //TODO determine how we can change the filters for an existing registered item
            //ServiceBusNamespaceClient

            lock (lockObject) {

                logger.Info("CreateSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3} Custom Attribute {4}",
                    value.SubscriptionName,
                    value.DeclaredType.ToString(),
                    value.MessageType.ToString(),
                    value.IsReusable,
                    value.AttributeData != null ? value.AttributeData.ToString() : string.Empty);
                logger.Info("TRANSIENT ERROR HANDLING CAN CAUSE THIS CHECK TO TAKE UP TO 10 SECONDS IF THE SUBSCRIPTION DOES NOT EXIST");

                SubscriptionDescription desc = null;

                bool createNew = false;

                try {
                    logger.Info("CreateSubscription Try {0} ", value.SubscriptionName);
                    // First, let's see if a item with the specified name already exists.
                    minimalRetryPolicy.ExecuteAction(() => {
                        desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                    });

                    createNew = (topic == null);
                }
                catch (MessagingEntityNotFoundException) {
                    logger.Info("CreateSubscription Does Not Exist {0} ", value.SubscriptionName);
                    // Looks like the item does not exist. We should create a new one.
                    createNew = true;
                }

                // If a item with the specified name doesn't exist, it will be auto-created.
                if (createNew) {
                    var descriptionToCreate = new SubscriptionDescription(topic.Path, value.SubscriptionName);

                    if (value.AttributeData != null) {
                        var attr = value.AttributeData;
                        if (attr.DefaultMessageTimeToLiveSet()) {
                            descriptionToCreate.DefaultMessageTimeToLive = new TimeSpan(0, 0, attr.DefaultMessageTimeToLive);
                        }
                        descriptionToCreate.EnableBatchedOperations = attr.EnableBatchedOperations;
                        descriptionToCreate.EnableDeadLetteringOnMessageExpiration = attr.EnableDeadLetteringOnMessageExpiration;
                        if (attr.LockDurationSet()) {
                            descriptionToCreate.LockDuration = new TimeSpan(0, 0, attr.LockDuration);
                        }
                    }

                    try {
                        logger.Info("CreateSubscription CreateTopic {0} ", value.SubscriptionName);
                        var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                        retryPolicy.ExecuteAction(() => {
                            desc = namespaceManager.CreateSubscription(descriptionToCreate, filter);
                        });
                    }
                    catch (MessagingEntityAlreadyExistsException) {
                        logger.Info("CreateSubscription GetTopic {0} ", value.SubscriptionName);
                        // A item under the same name was already created by someone else, perhaps by another instance. Let's just use it.
                        retryPolicy.ExecuteAction(() => {
                            desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                        });
                    }
                }

                SubscriptionClient subscriptionClient = null;
                var rm = ReceiveMode.PeekLock;

                if (value.AttributeData != null) {
                    rm = value.AttributeData.ReceiveMode;
                }

                retryPolicy.ExecuteAction(() => {
                    subscriptionClient = factory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, rm);
                });

                if (value.AttributeData != null && value.AttributeData.PrefetchCountSet()) {
                    subscriptionClient.PrefetchCount = value.AttributeData.PrefetchCount;
                }

                var state = new AzureBusReceiverState() {
                    Client = subscriptionClient,
                    EndPointData = value,
                    Subscription = desc
                };


                var helper = new AzureReceiverHelper(retryPolicy, state);
                mappings.Add(helper);
                helper.ProcessMessagesForSubscription();

            } //lock end

        }
        internal static List<Bookmark> GetBookmarksForDisplay()
        {
            SqlFilter filter = new SqlFilter(typeof(Bookmark));
            filter.AddConstraint("islocaldeleted", false);

            // return...
            return filter.ExecuteEntityCollection<Bookmark>();
        }
        void Configure(ServiceBusEnpointData value) {

            SubscriptionDescription desc = null;

            bool createNew = false;

            try {
                logger.Info("CreateSubscription Try {0} ", value.SubscriptionNameDebug);
                // First, let's see if a item with the specified name already exists.
                verifyRetryPolicy.ExecuteAction(() => {
                    desc = configurationFactory.NamespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                });

                createNew = (desc == null);
            }
            catch (MessagingEntityNotFoundException) {
                logger.Info("CreateSubscription Does Not Exist {0} ", value.SubscriptionNameDebug);
                // Looks like the item does not exist. We should create a new one.
                createNew = true;
            }

            // If a item with the specified name doesn't exist, it will be auto-created.
            if (createNew) {
                var descriptionToCreate = new SubscriptionDescription(topic.Path, value.SubscriptionName);

                if (value.AttributeData != null) {
                    var attr = value.AttributeData;
                    if (attr.DefaultMessageTimeToLiveSet()) {
                        descriptionToCreate.DefaultMessageTimeToLive = new TimeSpan(0, 0, attr.DefaultMessageTimeToLive);
                    }
                    descriptionToCreate.EnableBatchedOperations = attr.EnableBatchedOperations;
                    descriptionToCreate.EnableDeadLetteringOnMessageExpiration = attr.EnableDeadLetteringOnMessageExpiration;
                    if (attr.LockDurationSet()) {
                        descriptionToCreate.LockDuration = new TimeSpan(0, 0, attr.LockDuration);
                    }
                }

                try {
                    logger.Info("CreateSubscription {0} ", value.SubscriptionNameDebug);
                    var filter = new SqlFilter(string.Format(AzureSenderReceiverBase.TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                    retryPolicy.ExecuteAction(() => {
                        desc = configurationFactory.NamespaceManager.CreateSubscription(descriptionToCreate, filter);
                    });
                }
                catch (MessagingEntityAlreadyExistsException) {
                    logger.Info("CreateSubscription {0} ", value.SubscriptionNameDebug);
                    // A item under the same name was already created by someone else, perhaps by another instance. Let's just use it.
                    retryPolicy.ExecuteAction(() => {
                        desc = configurationFactory.NamespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                    });
                }
            }

            ISubscriptionClient subscriptionClient = null;
            var rm = ReceiveMode.PeekLock;

            if (value.AttributeData != null) {
                rm = value.AttributeData.ReceiveMode;
            }

            retryPolicy.ExecuteAction(() => {
                subscriptionClient = configurationFactory.MessageFactory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, rm);
            });

            if (value.AttributeData != null && value.AttributeData.PrefetchCountSet()) {
                subscriptionClient.PrefetchCount = value.AttributeData.PrefetchCount;
            }

            if (data == null) {
                data = new AzureBusReceiverState() {
                    EndPointData = value,
                    Client = subscriptionClient
                };
            }
            else {
                //we need to clean up the deleted subscription
                var oldClient = this.data.Client;

                data.Client = subscriptionClient;

                //now lets dispose the client.
                ExtensionMethods.ExecuteAndReturn(() => {
                    if (oldClient != null) {
                        oldClient.Close();
                    }
                });
            }
        }
        private void SetupAzureServiceBus()
        {
            Composable.GetExport<IXLogger>().Debug("Azure ServiceBus Scaling - INIT");
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(_connString);
            try
            {
                TopicDescription myTopic = null;

                if (!namespaceManager.TopicExists(TopicName))
                {
                    Composable.GetExport<IXLogger>().Debug("Creating Topic for Azure Service Bus");
                    myTopic = namespaceManager.CreateTopic(TopicName);
                }
                else
                {
                    Composable.GetExport<IXLogger>().Debug("Getting Topic for Azure Service Bus");
                    myTopic = namespaceManager.GetTopic(TopicName);
                }

                if (namespaceManager.SubscriptionExists(myTopic.Path, SID))
                {
                    Composable.GetExport<IXLogger>().Debug("Delete old subscription for Azure Service Bus");
                    namespaceManager.DeleteSubscription(myTopic.Path, SID);
                }
                Composable.GetExport<IXLogger>().Debug("Creating Subscription for Azure Service Bus");
                var filter = new SqlFilter(string.Format("SID != '{0}'", SID));
                namespaceManager.CreateSubscription(TopicName, SID, filter);

                this._topicClient = TopicClient.CreateFromConnectionString(_connString, myTopic.Path);
                this._subscriptionClient = SubscriptionClient.CreateFromConnectionString(_connString, myTopic.Path, SID);
            }
            catch (MessagingException e)
            {
                Composable.GetExport<IXLogger>().Error("Failed to setup scaling with Azure Service Bus: {e}", e.Message);
            }
        }
Пример #55
0
 private bool ValidateParameters()
 {
     try
     {
         if (string.IsNullOrWhiteSpace(txtMessageText.Text))
         {
             writeToLog(MessageCannotBeNull);
             return false;
         }
         int temp;
         if (string.IsNullOrWhiteSpace(txtReceiveTimeout.Text) ||
             !int.TryParse(txtReceiveTimeout.Text, out temp) ||
             temp < 0)
         {
             writeToLog(ReceiveTimeoutCannotBeNull);
             return false;
         }
         receiveTimeout = temp;
         if (string.IsNullOrWhiteSpace(txtServerTimeout.Text) ||
             !int.TryParse(txtServerTimeout.Text, out temp) ||
             temp < 0)
         {
             writeToLog(SessionTimeoutCannotBeNull);
             return false;
         }
         sessionTimeout = temp;
         if (string.IsNullOrWhiteSpace(txtPrefetchCount.Text) ||
             !int.TryParse(txtPrefetchCount.Text, out temp))
         {
             writeToLog(PrefetchCountCannotBeNull);
             return false;
         }
         prefetchCount = temp;
         if (!int.TryParse(txtMessageCount.Text, out temp) || temp < 0)
         {
             writeToLog(MessageCountMustBeANumber);
             return false;
         }
         messageCount = temp;
         if (!int.TryParse(txtSendBatchSize.Text, out temp) || temp <= 0)
         {
             writeToLog(SenderBatchSizeMustBeANumber);
             return false;
         }
         senderBatchSize = temp;
         if (!int.TryParse(txtReceiveBatchSize.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiverBatchSizeMustBeANumber);
             return false;
         }
         receiverBatchSize = temp;
         if (!int.TryParse(txtSenderThinkTime.Text, out temp) || temp <= 0)
         {
             writeToLog(SenderThinkTimeMustBeANumber);
             return false;
         }
         senderThinkTime = temp;
         if (!int.TryParse(txtReceiverThinkTime.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiverThinkTimeMustBeANumber);
             return false;
         }
         receiverThinkTime = temp;
         if (!int.TryParse(txtSendTaskCount.Text, out temp) || temp <= 0)
         {
             writeToLog(SendTaskCountMustBeANumber);
             return false;
         }
         senderTaskCount = temp;
         if (!int.TryParse(txtReceiveTaskCount.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiveTaskCountMustBeANumber);
             return false;
         }
         receiverTaskCount = temp;
         var sqlFilter = new SqlFilter(!string.IsNullOrWhiteSpace(txtFilterExpression.Text)
                                                           ? txtFilterExpression.Text
                                                           : DefaultFilterExpression);
         sqlFilter.Validate();
         filter = sqlFilter.Preprocess();
         if (filter == null)
         {
             writeToLog(FilterExpressionIsNotValid);
         }
         if (messageTabControl.SelectedIndex == FilesTabPage)
         {
             var fileList = messageFileListView.Items.Cast<ListViewItem>()
                         .Where(i => i.Checked)
                         .Select(i => i.Text)
                         .ToList();
             if (fileList.Count == 0)
             {
                 writeToLog(NoMessageSelected);
                 return false;
             }
         }
         if (messageTabControl.SelectedIndex == GeneratorTabPage && cboBrokeredMessageGeneratorType.SelectedIndex < 1)
         {
             writeToLog(string.Format(SelectBrokeredMessageGeneratorWarning, topic.Path));
             return false;
         }
     }
     catch (Exception ex)
     {
         HandleException(ex);
         return false;
     }
     return true;
 }
Пример #56
0
        /// <summary>
        /// This is a shared function that can be used to get an array of EstimateRecord records using a where and order by clause clause with pagination.
        /// </summary>
        public static EstimateRecord[] GetRecords(string where, OrderBy orderBy, int pageIndex, int pageSize)
        {
            SqlFilter whereFilter = null;
            if (where != null && where.Trim() != "")
            {
               whereFilter = new SqlFilter(where);
            }
            BaseClasses.Data.BaseFilter join = null;
            ArrayList recList = EstimateTable.Instance.GetRecordList(join, whereFilter, null, orderBy, pageIndex, pageSize);

            return (EstimateRecord[])recList.ToArray(Type.GetType("FPCEstimate.Business.EstimateRecord"));
        }
        internal static Bookmark GetByOrdinal(int ordinal)
        {
            SqlFilter filter = new SqlFilter(typeof(Bookmark));
            filter.AddConstraint("ordinal", ordinal);
            filter.AddConstraint("islocaldeleted", false);

            // return...
            return filter.ExecuteEntity<Bookmark>();
        }
Пример #58
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

            // Obtengo la connectionString que está almacenada en el app.config
            connectionString = ConfigurationManager.AppSettings["CitaTallerAzureBusSubscribe"];

            // También creo la suscripción para un taller en concreto
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            if (!namespaceManager.SubscriptionExists(topicName, SubscripName))
            {
                // Defino un filtro para un taller. Y creo la suscripción con ese filtro.
                SqlFilter DmsTallerIdFilter = new SqlFilter("DmsTallerId = '" + DmsTallerId + "'");
                namespaceManager.CreateSubscription(topicName, SubscripName, DmsTallerIdFilter);
            }

            // Creo un cliente para este NameSpace + Topic + Subscription
            // El cliente recibirá los mensajes en el evento onMessage
            SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, SubscripName);

            // Defino las opciones para el callback (evento)
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            Console.WriteLine("\nA la espera  ...");
            // Definimos el callback (event)
            Client.OnMessage((message) =>
                {
                    try
                    {
                        // Process message from subscription.
                        // Console.WriteLine("\n**High Messages**");
                        //Console.WriteLine("Body: " + message.GetBody<string>());
                        //Console.WriteLine("MessageID: " + message.MessageId);
                        //Console.WriteLine("Message Number: " +       message.Properties["MessageNumber"]);

                        // Mostramos en pantalla que hemos recibido un mensaje

                        Console.WriteLine("\nMensaje recibido:");
                        Console.WriteLine("Solicitud ID=" + message.Properties["SolicitudID"]);
                        Console.WriteLine("Taller ID=" + message.Properties["DmsTallerId"]);

                        // Eliminamos el mensaje de la suscripción
                        message.Complete();
                    }
                    catch (Exception ex)
                    {
                        // Hemos tenido un crash. Liberamos el mensaje y quedará pendiente.
                        message.Abandon();
                        Console.WriteLine(ex.Message);
                    }
                }, options);
            while (true)
            {
            }
        }
Пример #59
0
        public bool Start(string dmsTallerId)
        {
            try
            {
                //connectionString = ConfigurationManager.AppSettings["CitaTallerAzureBusSubscribe"];
                var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                if (!namespaceManager.SubscriptionExists(topicName, SubscripName))
                {
                    // Defino un filtro para un taller. Y creo la suscripción con ese filtro.
                    dmsTallerId = dmsTallerId.Replace("-", "").Trim().ToUpper();
                    if (string.IsNullOrEmpty(dmsTallerId))
                        {
                        namespaceManager.CreateSubscription(topicName, SubscripName);
                        }
                    else
                        {
                        SqlFilter DmsTallerIdFilter = new SqlFilter("DmsTallerId = '" + dmsTallerId + "'");
                        namespaceManager.CreateSubscription(topicName, SubscripName, DmsTallerIdFilter);
                        }
                }
                // Creo un cliente para este NameSpace + Topic + Subscription
                Client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, SubscripName);
                Connected = true;
                // Defino las opciones para el callback (evento)
                ClientOptions = new OnMessageOptions();
                ClientOptions.AutoComplete = false;
                ClientOptions.MaxConcurrentCalls = 1;
                ClientOptions.AutoRenewTimeout = TimeSpan.FromMinutes(1);
            }
            catch (Exception ex)
            {
                Connected = false;
                ErrorMsg(ex.Message);
            }

                // Definimos el callback (event)
            Client.OnMessage((busMessage) =>
            {
                try
                {
                    if (Closing)
                    {
                        busMessage.Abandon();
                        return;
                    }

                    Message message = new Message();
                    message.SolicitudID = busMessage.Properties["SolicitudID"].ToString();
                    message.DmsTallerId = busMessage.Properties["DmsTallerId"].ToString();

                    OcxOnMessage(message);
                    // Eliminamos el mensaje de la suscripción
                    busMessage.Complete();
                }
                catch (Exception ex)
                {
                    // Hemos tenido un crash. Liberamos el mensaje y quedará pendiente.
                    busMessage.Abandon();
                    ErrorMsg(ex.Message);
                }
            }, ClientOptions);
            return true;
        }
 private bool ValidateParameters()
 {
     try
     {
         if (string.IsNullOrEmpty(txtMessageText.Text))
         {
             writeToLog(MessageCannotBeNull);
             return false;
         }
         int temp;
         if (string.IsNullOrEmpty(txtReceiveTimeout.Text) ||
             !int.TryParse(txtReceiveTimeout.Text, out temp) ||
             temp <= 0)
         {
             writeToLog(ReceiveTimeoutCannotBeNull);
             return false;
         }
         receiveTimeout = temp;
         if (string.IsNullOrEmpty(txtSessionTimeout.Text) ||
             !int.TryParse(txtSessionTimeout.Text, out temp) ||
             temp <= 0)
         {
             writeToLog(SessionTimeoutCannotBeNull);
             return false;
         }
         sessionTimeout = temp;
         if (string.IsNullOrEmpty(txtPrefetchCount.Text) ||
             !int.TryParse(txtPrefetchCount.Text, out temp))
         {
             writeToLog(PrefetchCountCannotBeNull);
             return false;
         }
         prefetchCount = temp;
         if (!int.TryParse(txtMessageCount.Text, out temp) || temp < 0)
         {
             writeToLog(MessageCountMustBeANumber);
             return false;
         }
         messageCount = temp;
         if (!int.TryParse(txtSendTaskCount.Text, out temp) || temp <= 0)
         {
             writeToLog(SendTaskCountMustBeANumber);
             return false;
         }
         senderTaskCount = temp;
         if (!int.TryParse(txtReceiveTaskCount.Text, out temp) || temp <= 0)
         {
             writeToLog(ReceiveTaskCountMustBeANumber);
             return false;
         }
         receiverTaskCount = temp;
         var sqlFilter = new SqlFilter(!string.IsNullOrEmpty(txtFilterExpression.Text)
                                                           ? txtFilterExpression.Text
                                                           : DefaultFilterExpression);
         sqlFilter.Validate();
         filter = sqlFilter.Preprocess();
         if (filter == null)
         {
             writeToLog(FilterExpressionIsNotValid);
         }
     }
     catch (Exception ex)
     {
         mainForm.HandleException(ex);
         return false;
     }
     return true;
 }